【问题标题】:C# Get last day of previous month given a month and year给定月份和年份的C#获取上个月的最后一天
【发布时间】:2019-05-03 13:27:28
【问题描述】:

我正在尝试创建一个返回 DateTime 对象的方法。

这个日期应该是上个月的最后一天(月份是我给的)。

例子:

月份:一月 (1)

年份: 2019

我需要什么: 2018 年 12 月 31 日

这就是我所拥有的

   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;
        }

但它返回错误:

只有赋值、调用、递增、递减和新对象表达式可以用作语句

我做错了什么?

【问题讨论】:

  • 你想要date.Month = month而不是date.Month == month(年份相同)
  • 返回另一个错误:Property or indexer 'DateTime.Month' cannot be assigned to -- it is read only

标签: c# datetime


【解决方案1】:

怎么样:

public DateTime GetLastDayPrevMonth(int month, int year)
{
    return new DateTime(year, month, 1).AddDays(-1);
}

这将为给定月/年的第一天创建一个新的 DateTime 对象。然后从该月的第一天减去一天,留下上个月的最后一天。

【讨论】:

    【解决方案2】:

    你可以得到Current Datelike

    var CurrentDate= DateTime.Now; 
    

    Current Month的第一天点赞

    var FirstdayOfThisMonth= new DateTime(CurrentDate.Year, CurrentDate.Month, 1);
    

    您可以添加-1,它将返回previous month 的最后一天

    var lastDayOfLastMonth = FirstdayOfThisMonth.AddDays(-1);
    

    【讨论】:

    • 除了你应该在一般情况下使用.Today而不是.Now
    • 是的,先生,但是两者都给出了相同的结果,今天使用而不是现在,谢谢?
    • @ArunPratap 根本不需要CurrentDate,如果你想看看OP的问题。
    • @BoredomOverload 是的兄弟,但堆栈溢出不是代码编写服务,我已经描述了 op 如何做到这一点,谢谢
    猜你喜欢
    • 1970-01-01
    • 2014-11-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-29
    • 1970-01-01
    • 1970-01-01
    • 2017-12-04
    相关资源
    最近更新 更多