Calculating for remaining days in current month [duplicate] - c#

This question already has answers here:
How to find the first day of next month,if the current month is december
(12 answers)
Calculate difference between two dates (number of days)?
(17 answers)
Closed 5 years ago.
I would like to know how to calculate the remaining days of the month e.g (15 Feb 2017 to 28 Feb 2017) without the use of a datetimepicker set at 28 Feb 2017.
Here are my codes for subtraction of 2 datetimepicker:
DateTime startDate =
(DateTime)dateTimePicker2.Value;
DateTime endDate =
(DateTime)dateTimePicker1.Value;
TimeSpan ts = endDate.Subtract(startDate);
textBox10.Text = ts.Days.ToString();`

Here are the steps you need to go through:
take your current date
use DateTime.AddMonths() to generate a new date one month from your current date
create a new date that uses 1 for the day, and the month and year from the future date you just worked out
subtract your current date from the future date, this will give you a Timespan which contains the number of days difference
You can use the closely related question Calculate difference between two dates (number of days)? as a guide.

Here is an example, but you can use the Value property from your DateTimePicker instead. DateTime.DaysInMonth(int year, int month) is a helpful method.
DateTime beginDate = new DateTime(2017, 2, 15);
var daysLeft = DateTime.DaysInMonth(beginDate.Year, beginDate.Month) - beginDate.Day;
Console.WriteLine("days from Feb 15 to Feb 28: {0}", daysLeft);
Output:
days from Feb 15 to Feb 28: 13

You can try:
DateTime dt = DateTime.Now;
int days = dt.AddDays(1 - dt.Day).AddMonths(1).AddDays(-1).Day - dt.Day;

Related

How can we get Monthly(Day-Of-Week) for backup purpose [duplicate]

This question already has answers here:
Get DateTime of the next nth day of the month
(5 answers)
How to calculate 2nd Friday of Month in C# [duplicate]
(4 answers)
Closed 3 years ago.
I want to get a next backup date using (day-of-week) monthly for a scheduled backup.
If I took a backup on Monday, second week, Jan-2019, then Next backup date should be Monday in the second week of February-2019.
So, How can we get the specific day as per the given week for every coming month?
Now I'm getting the next backup month but I'm not sure how we get the same Day in a specfic week.
You should create an extension method for DateTime class.
public static DateTime NthOf(this DateTime CurDate, int Occurrence , DayOfWeek Day)
{
var fday = new DateTime(CurDate.Year, CurDate.Month, 1);
var fOc = fday.DayOfWeek == Day ? fday : fday.AddDays(Day - fday.DayOfWeek);
if (fOc.Month < CurDate.Month) Occurrence = Occurrence+1;
return fOc.AddDays(7 * (Occurrence - 1));
}
And use
new DateTime().NthOf(2, DayOfWeek.Monday))
Refer: How to calculate 2nd Friday of Month in C#
Why dont you get the DayOfTheYear and just add 7 to it. Something like this:
var dateTime = DateTime.Now;
var dayOfYear = dateTime.DayOfYear;
var nextDate = dateTime.AddDays(dayOfYear + 7);
Console.WriteLine(nextDate);
Since the next backup day is the same day, which means just add 7 to it. You will have to manage the last week of year though in this case

C# date rolling 13 months values in global variable .NET

In C# how do I get the below datetime values in .NET. I am trying to look at todays date and trying to get a rolling 13 months. So last month minus 13 months which is december 2017 but need to get first day of the month at 00:00:00.000. Also trying to get an enddate as below which is end of last month.
Trying to get this and assign it to a variable in my code.
StartDate:
2017-12-01 00:00:00.000
EndDate:
2019-01-31 23:59:59.000
Whats the best way to get this?
Here you go
DateTime mydate = DateTime.Today;
//2017-12-01 00:00:00.000
DateTime StartDate = new DateTime(mydate.Year, mydate.Month, 1).AddMonths(-14);
//2019-01-31 23:59:59.000
DateTime EndDate = new DateTime(mydate.Year, mydate.Month, 1).AddSeconds(-1);
You can get the date with DateTime date = DateTime.Today.AddMonths(-14).AddDays(-(DateTime.Today.Day - 1));
.AddMonths(-13) yielded january 2018 for me

DateTime is not equal [duplicate]

This question already has answers here:
Is there any difference between DateTime in c# and DateTime in SQL server?
(3 answers)
Closed 7 years ago.
I have next code:
DateTime endTime = DateTime.Now.AddDays(30);
InsertIntoDatabase(endTime);
var row = Db.SelectRow("select endTime from MyTable Where #column=myval", columnValue);
Assert.Equal(row["endTime"], endTime); // This is false! Why?
Assert is false.
And dates are different for some reason on milliseconds. Why???
endTime:
Date {7/17/2015 12:00:00 AM} System.DateTime
Day 17 int
DayOfWeek Friday System.DayOfWeek
DayOfYear 198 int
Hour 1 int
Kind Unspecified System.DateTimeKind
Millisecond 370 int
Minute 21 int
Month 7 int
Second 27 int
Ticks 635726928873700000 long
+ TimeOfDay {01:21:27.3700000} System.TimeSpan
Year 2015 int
row["endTime"]:
Date {7/17/2015 12:00:00 AM} System.DateTime
Day 17 int
DayOfWeek Friday System.DayOfWeek
DayOfYear 198 int
Hour 1 int
Kind Local System.DateTimeKind
Millisecond 371 int
Minute 21 int
Month 7 int
Second 27 int
Ticks 635726928873716049 long
+ TimeOfDay {01:21:27.3716049} System.TimeSpan
Year 2015 int
WHY???
Maybe this (Difference between DateTime in c# and DateTime in SQL server) will help a little.
you can also use Datetime2 for SQL
Looks like a rounding error to me, the DateTime has ticks of 635726928873700000 whereas the Row has 635726928873716049. This is probably due to differing levels of precision in the database vs DateTime.
The differences in ticks means they are different DateTimes.

Finding the date of monday in a week with asp.net [duplicate]

This question already has answers here:
DateTime question in VB.NET
(3 answers)
Closed 9 years ago.
I need to find the date of Monday this week.
For example, for this week Monday was on the 25th, so the date I need is: 25/02/2013
And when we roll over to next week it needs to calculate: 03/03/2013.
I tried to search but i cant find it for asp.net.
DateTime mondayDate = DateTime
.Today
.AddDays(((int)(DateTime.Today.DayOfWeek) * -1) + 1);
So for Today {27/02/2013 12:00:00 AM} it will give {25/02/2013 12:00:00 AM}
Usage in C#:
dt.AddDays(1 - (dt.DayOfWeek == DayOfWeek.Sunday ? 7 : (int)dt.DayOfWeek));
Usage in VB.NET:
dt.AddDays(1 - If(dt.DayOfWeek = DayOfWeek.Sunday, 7, dt.DayOfWeek))
Reference: DateTime question in VB.NET

c# find same range of "named days" from 1 year ago

using c# visual studio 2008.
Can anyone help with an algorithm to do this please
if i have a range of days selected for this week (eg monday to friday) i can find the dates for these using the datetime functions available.
What i want to do is compared to stored data for the same DAY range 1 year ago.
So basicly i need to go back 1 year and find the dates for the nearest Mon to fri DAY range from 1 year previous. I guess i also need to take into acount leap years.
Can anyone help with a suitable algorithm on how to achieve this.
Of course the DAY for todays date last year is not going to be the same day.
thanks in advance
Here's some code which might do what you want - but the test cases show that there are corner cases to consider:
using System;
public class Test
{
static void Main()
{
Console.WriteLine(SameDayLastYear(DateTime.Today));
Console.WriteLine(SameDayLastYear(new DateTime(2010, 12, 31)));
}
static DateTime SameDayLastYear(DateTime original)
{
DateTime sameDate = original.AddYears(-1);
int daysDiff = original.DayOfWeek - sameDate.DayOfWeek;
return sameDate.AddDays(daysDiff);
}
}
What would you want the result for the second call to be? This code returns January 1st 2010, because that's the closest date to "a year ago on the same day".
I strongly suggest that whatever you go with, you have unit tests checking leap years, start and end of year etc.
Let's say you select Wednesday 10-02-2010 - Friday 12-02-2010 this year.
Last year that would have been Tuesday 10-02-2009 - Thursday 12-02-2009.
So you can do the following: Go back a year by simply performing DateTime.AddYears(-1). Make sure you correct for leap years here.
Then you use .AddDays(1) until you end up on a Wednesday - Friday timeframe.
That way you only have to take leap years into account at one point and this should produce the result you need.
I just subtracted one year then ran backwards until I found a Monday. LastYear will end up being the first Monday before this date last year
DateTime LastYear = DateTime.Now.AddYears(-1)
DayOfWeek Check = LastYear.DayOfWeek;
while (Check != DayOfWeek.Monday)
{
LastYear = LastYear.addDays(-1);
Check = LastYear.DayOfWeek;
}
Console.WriteLine("{0}",LastYear);
DateTime now = DateTime.Now;
DateTime lastyear = now.AddYears(-1);
string dayOfWeek = lastyear.DayOfWeek.ToString();
if (dayOfWeek.Equals("Saturday")) { dayOfWeek = "Friday"; }
else if (dayOfWeek.Equals("Sunday")) { dayOfWeek = "Monday"; }
Console.WriteLine(dayOfWeek);
Console.ReadKey();
Get a datetime object for last year, then use the DayOfWeek property.
This was pretty fun.
// today's info
DateTime today = DateTime.Now;
DayOfWeek today_name = today.DayOfWeek;
// this day one year ago
DateTime year_ago = today - new TimeSpan( ((today.Year - 1) % 4) ? 365 : 366, 0, 0, 0);
// find the closest day to today's info's name
DayOfWeek today_name_a_year_ago = year_ago.DayOfWeek;
DateTime current_range_a_year_ago = year_ago - new TimeSpan( year_ago.DayOfWeek - today_name, 0, 0, 0);
Console.WriteLine( "Today is {0}, {1}", today_name, today);
Console.WriteLine( "One year from today was {0}, {1}", today_name_a_year_ago, year_ago);
Console.WriteLine( "New date range is {0}", current_range_a_year_ago);
I would highly recommend using the unit testing features built into VS2008 to make sure you account for corner cases.

Categories