[英]C# Get last day of previous month given a month and year
I'm trying to create a method that returns me a DateTime object. 我正在尝试创建一个向我返回DateTime对象的方法。
This date should be the last day of the previous month (month is given by me). 这个日期应该是上个月的最后一天(我给的月份)。
Example: 例:
Month: january (1) 月:一月(1)
Year: 2019 年: 2019
What I need: 31/12/2018 我需要: 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. 这将在给定的月份/年份的第一天创建一个新的DateTime对象。 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 你可以得到
Current Date
像
var CurrentDate= DateTime.Now;
and first day of Current Month
like 和
Current Month
第一天
var FirstdayOfThisMonth= new DateTime(CurrentDate.Year, CurrentDate.Month, 1);
and you can add -1
that will return last day of previous month
like 您可以添加
-1
,将最后一天返回的previous month
像
var lastDayOfLastMonth = FirstdayOfThisMonth.AddDays(-1);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.