C# Get last day of previous month given a month and year - c#

I'm trying to create a method that returns me a DateTime object.
This date should be the last day of the previous month (month is given by me).
Example:
Month: january (1)
Year: 2019
What I need: 31/12/2018
This is what I have
public DateTime getLastDayPrevMonth(int month, int year)
{
DateTime date = new DateTime();
date.Month == month;
date.Year == year;
date.AddMonths(-1);
date.Day = DateTime.DaysInMonth(date.Year,date.Month);
return date;
}
but it returns the error:
Only assignment, call, increment, decrement, and new object expressions can be used as a statement
What am I doing wrong?

How about:
public DateTime GetLastDayPrevMonth(int month, int year)
{
return new DateTime(year, month, 1).AddDays(-1);
}
This creates a new DateTime Object for the first day in the given Month/Year. Then it subtracts one day off of the first day of the month, leaving you with the last day of the previous month.

you can get Current Date like
var CurrentDate= DateTime.Now;
and first day of Current Month like
var FirstdayOfThisMonth= new DateTime(CurrentDate.Year, CurrentDate.Month, 1);
and you can add -1 that will return last day of previous month like
var lastDayOfLastMonth = FirstdayOfThisMonth.AddDays(-1);

Related

Get DateTime of the next nth day of the month

If given a date and a variable n, how can I calculate the DateTime for which the day of the month will be the nth Date?
For example, Today is the 17th of June.
I would like a function that when provided 15 would return the DateTime for July 15.
A few more examples:
Today is Feb. 26: Function would return March 30 when provided 30.
Today is Dec. 28. Function would return Jan 4 when provided 4.
Today is Feb. 28. Function would return March 29 when provided 29, unless it was a leap year, in which case it would return Feb 29.
Why not just do?
private DateTime GetNextDate(DateTime dt, int DesiredDay)
{
if (DesiredDay >= 1 && DesiredDay <= 31)
{
do
{
dt = dt.AddDays(1);
} while (dt.Day != DesiredDay);
return dt.Date;
}
else
{
throw new ArgumentOutOfRangeException();
}
}
After many, many edits, corrections and re-writes, here is my final answer:
The method that follows returns a a DateTime representing the next time the day of number day comes up in the calendar. It does so using an iterative approach, and is written in the form of an extension method for DateTime objects, and thus isn't bound to today's date but will work with any date.
The code executes the following steps to get the desired result:
Ensure that the day number provided is valid (greater than zero and smaller than 32).
Enter into a while loop that keeps going forever (until we break).
Check if cDate's month works (the day must not have passed, and the month must have enough days in it).
If so, return.
If not, increase the month by one, set the day to one, set includeToday to true so that the first day of the new month is included, and execute the loop again.
The code:
static DateTime GetNextDate3(this DateTime cDate, int day, bool includeToday = false)
{
// Make sure provided day is valid
if (day > 0 && day <= 31)
{
while (true)
{
// See if day has passed in current month or is not contained in it at all
if ((includeToday && day > cDate.Day || (includeToday && day >= cDate.Day)) && day <= DateTime.DaysInMonth(cDate.Year, cDate.Month))
{
// If so, break and return
break;
}
// Advance month by one and set day to one
// FIXED BUG HERE (note the order of the two calls)
cDate = cDate.AddDays(1 - cDate.Day).AddMonths(1);
// Set includeToday to true so that the first of every month is taken into account
includeToday = true;
}
// Return if the cDate's month contains day and it hasn't passed
return new DateTime(cDate.Year, cDate.Month, day);
}
// Day provided wasn't a valid one
throw new ArgumentOutOfRangeException("day", "Day isn't valid");
}
The spec is a little bit unclear about to do when today is the dayOfMonth. I assumed it was it to return the same. Otherwise it would just be to change to <= today.Day
public DateTime FindNextDate(int dayOfMonth, DateTime today)
{
var nextMonth = new DateTime(today.Year, today.Month, 1).AddMonths(1);
if(dayOfMonth < today.Day){
nextMonth = nextMonth.AddMonths(1);
}
while(nextMonth.AddDays(-1).Day < dayOfMonth){
nextMonth = nextMonth.AddMonths(1);
}
var month = nextMonth.AddMonths(-1);
return new DateTime(month.Year, month.Month, dayOfMonth);
}
Stumbled upon this thread today while trying to figure out this same problem.
From my testing, the following seems to work well and the loop only needs two goes (I think? Maybe 3 max(?)) to get to the answer:
public static DateTime GetNearestSpecificDay(DateTime start, int dayNum)
{
if (dayNum >= 1 && dayNum <= 31)
{
DateTime result = start;
while (result.Day != dayNum)
result = dayNum > result.Day ? result.AddDays(dayNum - result.Day) : new DateTime(result.Month == 12 ? result.Year + 1 : result.Year, (result.Month % 12) + 1, 1);
return result;
}
else
return DateTime.Today;
}
Edit: As requested, here's a less compact version that walks through the logic step by step. I've also updated the original code to account for a required year change when we reach December.
public static DateTime GetNearestSpecificDay(DateTime start, int dayNum)
{
// Check if target day is valid in the Gregorian calendar
if (dayNum >= 1 && dayNum <= 31)
{
// Declare a variable which will hold our result & temporary results
DateTime result = start;
// While the current result's day is not the desired day
while (result.Day != dayNum)
{
// If the desired day is greater than the current day
if (dayNum > result.Day)
{
// Add the difference to try and skip to the target day (if we can, if the current month does not have enough days, we will be pushed into the next month and repeat)
result = result.AddDays(dayNum - result.Day);
}
// Else, get the first day of the next month, then try the first step again (which should get us where we want to be)
else
{
// If the desired day is less than the current result day, it means our result day must be in the next month (it obviously can't be in the current)
// Get the next month by adding 1 to the current month mod 12 (so when we hit december, we go to january instead of trying to use a not real 13th month)
// If result.Month is November, 11%12 = 11; 11 + 1 = 12, which rolls us into December
// If result.Month is December, 12%12 = 0; 0 + 1 = 1, which rolls us into January
var month = (result.Month % 12) + 1;
// Get current/next year.
// Since we are adding 1 to the current month, we can assume if the previous month was 12 that we must be entering into January of next year
// Another way to do this would be to check if the new month is 1. It accomplishes the same thing but I chose 12 since it doesn't require an extra variable in the original code.
// Below can be translated as "If last result month is 12, use current year + 1, else, use current year"
var year = result.Month == 12 ? result.Year + 1 : result.Year;
// Set result to the start of the next month in the current/next year
result = new DateTime(year, month, 1);
}
}
// Return result
return result;
}
else
// If our desired day is invalid, just return Today. This can be an exception or something as well, just using Today fit my use case better.
return DateTime.Today;
}
Fun little puzzle. I generated 100 DateTimes which represent the starting day of each month, then checked each month to see if it had the date we want. It's lazy so we stop when we find a good one.
public DateTime FindNextDate(int dayOfMonth, DateTime today)
{
DateTime yesterday = today.AddDays(-1);
DateTime currentMonthStart = new DateTime(today.Year, today.Month, 1);
var query = Enumerable.Range(0, 100)
.Select(i => currentMonthStart.AddMonths(i))
.Select(monthStart => MakeDateOrDefault(
monthStart.Year, monthStart.Month, dayOfMonth,
yesterday)
.Where(date => today <= date)
.Take(1);
List<DateTime> results = query.ToList();
if (!results.Any())
{
throw new ArgumentOutOfRangeException(nameof(dayOfMonth))
}
return results.Single();
}
public DateTime MakeDateOrDefault(
int year, int month, int dayOfMonth,
DateTime defaultDate)
{
try
{
return new DateTime(year, month, dayOfMonth);
}
catch
{
return defaultDate;
}
}

Calculate Last Day of the Next Month

I am attempting to use the DateTime function in C# to calculate the last day of next month.
For example, today is December 17th 2015. I want the DateTime function to return January 31st 2016 (the last day of next month).
I am using the following to calculate the first day of next month (this works):
DateTime firstDayNextMonth = DateTime.Today.AddDays(-DateTime.Now.Day+1).AddMonths(1);
DateTime reference = DateTime.Now;
DateTime firstDayThisMonth = new DateTime(reference.Year, reference.Month, 1);
DateTime firstDayPlusTwoMonths = firstDayThisMonth.AddMonths(2);
DateTime lastDayNextMonth = firstDayPlusTwoMonths.AddDays(-1);
DateTime endOfLastDayNextMonth = firstDayPlusTwoMonths.AddTicks(-1);
Demo: http://rextester.com/AKDI52378
//system date or any date u want this case it is a calendar picker - 22/03/2016
DateTime today = dtpFrom.Value;
//Add a month to your date example , it now becomes - 22/04/2016
DateTime endOfMonth = new DateTime(today.Year, today.Month,today.Day).AddMonths(1);
//Get the last date off the above which is - 30
int getlastday = DateTime.DaysInMonth(endOfMonth.Year, endOfMonth.Month);
//Now set the date to the value which will be the last day off the next month - 30/04/2016
DateTime newDate = new DateTime(endOfMonth.Year, endOfMonth.Month, getlastday);
DateTime.DaysInMonth(DateTime.Now.AddMonths(1).Year, DateTime.Now.AddMonths(1).Month);
var lastDayInNextMonth = DateTime.DaysInMonth(DateTime.Now.AddMonths(1).Year, DateTime.Now.AddMonths(1).Month );
# Ben : DateTime.Now.AddMonths(1) will add 1 month to the current date not substract 11 months.
DateTime.Now.AddMonths(1).Year will give 2016 not 2015 refer the attached image
try this:
int Day= DateTime.DaysInMonth(DateTime.Now.Year, DateTime.Now.Month+1>12 ? 01 : DateTime.Now.Month+1 );

determine maximum number of days in particular month

from razor view I'm sending selected month and year to the controller using jquery.
Inside controller I'm receiving those selected values and create datetime properties
public ActionResult Index(int year, int month)
{
Date1 = new DateTime(year, month, 1);
Date2 = new DateTime(year, month, 31);
...
}
Some months has 31 day, some 30 and feb. has 28 (inside leap year 29) days.
My question is:
How can I recognize those months and based on that set appropriate max month day inside Date2 variable?
You could use the DaysInMonth method on DateTime:
Date2 = new DateTime(year, month, DateTime.DaysInMonth(year, month));
You want DateTime.DaysInMonth(year, month)

Getting date using day of the week

I have problem in finding the date using day of the week.
For example : i have past date lets say,
Date date= Convert.TodateTime("01/08/2013");
08th Jan 2013 th Day of the week is Tuesday.
Now i want current week's tuesday's date. How i can do it.
Note : The past date is dynamic. It will change in every loop.
You can use the enumeration DayOfWeek
The DayOfWeek enumeration represents the day of the week in calendars
that have seven days per week. The value of the constants in this
enumeration ranges from DayOfWeek.Sunday to DayOfWeek.Saturday. If
cast to an integer, its value ranges from zero (which indicates
DayOfWeek.Sunday) to six (which indicates DayOfWeek.Saturday).
We can use the conversion to integer to calculate the difference from the current date of the same week day
DateTime dtOld = new DateTime(2013,1,8);
int num = (int)dtOld.DayOfWeek;
int num2 = (int)DateTime.Today.DayOfWeek;
DateTime result = DateTime.Today.AddDays(num - num2);
This also seems appropriate to create an extension method
public static class DateTimeExtensions
{
public static DateTime EquivalentWeekDay(this DateTime dtOld)
{
int num = (int)dtOld.DayOfWeek;
int num2 = (int)DateTime.Today.DayOfWeek;
return DateTime.Today.AddDays(num - num2);
}
}
and now you could call it with
DateTime weekDay = Convert.ToDateTime("01/08/2013").EquivalentWeekDay();
I may be a bit late to the party, but my solution is very similar:
DateTime.Today.AddDays(-(int)(DateTime.Today.DayOfWeek - DayOfWeek.Tuesday));
This will get the Tuesday of the current week, where finding Tuesday is the primary goal (I may have misunderstood the question).
You can use this....
public static void Main()
{
//current date
DateTime dt = DateTime.UtcNow.AddHours(6);
//you can use it custom date
var cmYear = new DateTime(dt.Year, dt.Month, dt.Day);
//here 2 is the day value of the week in a date
var customDateWeek = cmYear.AddDays(-2);
Console.WriteLine(dt);
Console.WriteLine(cmYear);
Console.WriteLine("Date: " + customDateWeek);
Console.WriteLine();
Console.ReadKey();
}

how to get the days for particular month and year

I have a method which passes two parameters Month and year
i will call this Method like this : MonthDates(January,2010)
public static string MonthDates(string MonthName,string YearName)
{
return days;
}
How to get the days for particular month and year?
do you mean the number of days in a month?
System.DateTime.DaysInMonth(int year, int month)
If you want all days as a collection of DateTime:
public static IEnumerable<DateTime> daysInMonth(int year, int month)
{
DateTime day = new DateTime(year, month, 1);
while (day.Month == month)
{
yield return day;
day = day.AddDays(1);
}
}
The use is:
IEnumerable<DateTime> days = daysInMonth(2010, 07);
System.DateTime.Now.Month
System.DateTime.Now.Year
System.DateTime.Now.Day
And so on.........You have lots of things you can get from DateTime.Now
instead of string try to declare an enum like the following
public enum Month
{
January = 1,
February,
March,
.... so on
}
then pass it to the function of yours and use the followings in your function
return System.DateTime.DaysInMonth(year, month);
Instead of string try to use integer, as it will reduce the overhead of parsing strings.

Categories

Resources