如何从C#中的日期字符串获取本月的最后一天?

joe*_*den 2 c#

如何找到字符串中所述的当月最后一天?

例如,如果字符串是"2018年1月",我将如何记录31/01/2018作为日期

目前默认为本月的第一天:

string nextEventDateString = "January 2018"
DateTime tempDate;

if (DateTime.TryParse(nextEventDateString, out tempDate))
{
    cRecord.ComplianceDate = tempDate.ToString("dd/MM/yyyy");
    cRecord.NotifyDate = tempDate.AddMonths(-1).ToString("dd/MM/yyyy");
    cRecord.WarningDate = tempDate.AddMonths(1).ToString("dd/MM/yyyy");
}
Run Code Online (Sandbox Code Playgroud)

Hab*_*bib 10

首先将字符串解析为DateTime,稍后添加一个月并从日期中减去一天,它将为您提供该月的最后一天,如:

string dateString = "January 2018";
DateTime dt = DateTime.ParseExact(dateString, "MMMM yyyy", CultureInfo.InvariantCulture);

DateTime lastDateForMonth = dt.AddMonths(1).AddDays(-1);
Run Code Online (Sandbox Code Playgroud)

作为旁注,您似乎DateTime在对象属性中保留字符串表示形式.最好保留DateTime而不是string.在格式/表示中使用字符串表示.IMO.还可以继续使用DateTime.TryParseDateTime.TryParseExact使用格式,因为如果解析失败,它将使您免于异常.