Reputation: 524
DateTime dt = DateTime.UtcNow;
var lastDayOfMonth = DateTime.DaysInMonth(DateTime.Now.Year, DateTime.Now.Month);
day = dt.Day;
if (day != lastDayOfMonth)
{
if (dt.Hour >= 14)
{
day = day + 1;
}
else if (dt.DayOfWeek == DayOfWeek.Sunday)
day = day + 1;
}
else
{
//
}
Now I want to add one day to the last day of the month. How can i do it?
Upvotes: 3
Views: 1126
Reputation: 524
Finally i did this by removing the if condition for lastDayOfMonth and using AddDays property.
if (dt.Hour >= 14)
{
dt.AddDays(1);
}
else if (dt.DayOfWeek == DayOfWeek.Sunday)
{
dt.AddDays(1);
}
day = dt.Day;
thankyou everyone for your valuable suggestions.
Upvotes: 1
Reputation: 98740
Sounds like you just need DateTime.AddDays
method
Returns a new DateTime that adds the specified number of days to the value of this instance.
But DateTime.Day
property returns int
. If you just want to add it 1
, you are in a right way.
day = day + 1;
But this doesn't affect dt
of course.
Ok, let's look at your exact problem now..
Adding 1
month and then extracting 1
day is the one of the best way to find out the last day of the current month.
For example;
DateTime dt = DateTime.UtcNow;
var FirstDayOfNextMonth = new DateTime(dt.Year, dt.Month, 1).AddMonths(1);
var LastDayOfCurrentMonth = FirstDayOfNextMonth.AddDays(-1);
Console.WriteLine(LastDayOfCurrentMonth);
Output will be;
2/28/2014 12:00:00 AM
Here a demonstration
.
Upvotes: 2
Reputation: 3456
To find the first day of next month you can use
Datetime FirstDayofNxtMnth =DATE(YEAR(TODAY()),MONTH(TODAY())+1,1);
To find the Last day of this month you can use
Datetime FirstDayofNxtMnth =DATE(YEAR(TODAY()),MONTH(TODAY())+1,1);
Datetime LastDayofThisMnth =DATE(YEAR(TODAY()),MONTH(TODAY())+1,1).addDay(-1);
Upvotes: 1
Reputation: 241450
DateTime today = DateTime.Today;
DateTime firstDayOfThisMonth = new DateTime(today.Year, today.Month, 1);
DateTime firstDayOfNextMonth = firstDayOfThisMonth.AddMonths(1);
Upvotes: 1