简体   繁体   English

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

[英]How to get last Day of the Month from a date string in C#?

How would I find the last day of current month stated in the String? 如何找到字符串中所述的当月最后一天?

Eg if the string was "January 2018" how would I record 31/01/2018 as the date 例如,如果字符串是“2018年1月”,我将如何记录31/01/2018作为日期

Currently it defaults to the first of the month: 目前默认为本月的第一天:

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

First parse the string to DateTime , later add one month and subtract one day from the date, it will give you the last day for the month like: 首先将字符串解析为DateTime ,稍后添加一个月并从日期中减去一天 ,它将为您提供该月的最后一天,如:

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

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

As a side note, It appears you are keeping a string representation of DateTime in your object properties. 作为旁注,您似乎在对象属性中保留DateTime的字符串表示形式。 It would be better to keep DateTime instead of string . 保留DateTime而不是string会更好。 Use string representation in formatting/presentation. 在格式/表示中使用字符串表示。 IMO. IMO。 Also continue using DateTime.TryParse or DateTime.TryParseExact with a format, as it will save you from the exception in case of failed parsing. 还继续使用DateTime.TryParseDateTime.TryParseExact格式,因为它将在解析失败的情况下将您从异常中保存。

Using this: 使用这个:

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

You will get the number of days for the January of 2018. Then you could build your datetime like below: 您将获得2018年1月的天数。然后您可以构建您的日期时间,如下所示:

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

where in place of year and month you will place the year and the month you are interested in. 代替yearmonth您将放置您感兴趣的年份和月份。

In any case, you have to parse your string first and create a valid DateTime , in order you get the year, dt.Year and the month dt.Month ( dt is the parsed date time string). 在任何情况下,您必须首先解析您的字符串并创建一个有效的DateTime ,以便获得年份, dt.Year和月份dt.Monthdt是解析的日期时间字符串)。

Try this: 尝试这个:

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