簡體   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