繁体   English   中英

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

[英]How to get last Day of the Month from a date string in 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");
}

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

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

DateTime lastDateForMonth = dt.AddMonths(1).AddDays(-1);

作为旁注,您似乎在对象属性中保留DateTime的字符串表示形式。 保留DateTime而不是string会更好。 在格式/表示中使用字符串表示。 IMO。 还继续使用DateTime.TryParseDateTime.TryParseExact格式,因为它将在解析失败的情况下将您从异常中保存。

使用这个:

var days = DateTime.DaysInMonth(2018, 01);

您将获得2018年1月的天数。然后您可以构建您的日期时间,如下所示:

DateTime lastDayForMonth = new DateTime(year, month, days-1);

代替yearmonth您将放置您感兴趣的年份和月份。

在任何情况下,您必须首先解析您的字符串并创建一个有效的DateTime ,以便获得年份, dt.Year和月份dt.Monthdt是解析的日期时间字符串)。

尝试这个:

DateTime today = DateTime.Today;
DateTime endOfMonth = new DateTime(today.Year, today.Month, 1).AddMonths(1).AddDays(-1);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM