简体   繁体   English

C#日期时间范围

[英]C# datetime scope

Assuming I can not change service that returns data, I am left with 假设我无法更改返回数据的服务,那么我会

var date = "20140231";
var scope = DateTime.ParseExact(date, "yyyyMMdd", CultureInfo.CurrentCulture);

Clearly "20140231" is lazy way of saying end of February . 显然,“ 20140231”是2月底的懒惰说法。 What is the cleanest way to get last date of February with input of "20140231"? 输入“ 20140231”来获取二月的最后日期的最干净方法是什么?

There is 1 constraint - this should work with .net 2.0. 有1个约束-应该与.net 2.0兼容。

string date = "20140231";
DateTime result;
int year = Convert.ToInt32(date.Substring(0, 4));
int month = Convert.ToInt32(date.Substring(4, 2));
int day = Convert.ToInt32(date.Substring(6, 2));

result = new DateTime(year, month, Math.Min(DateTime.DaysInMonth(year, month), day));

February can have only 28 or 29 days depends on current year is a leap year or not. 二月 只能2829天取决于当年是闰年与否。

It can't have 30 or 31 days in any year. 一年中不能有3031天。 That's why you can't parse your 20140231 string successfully. 这就是为什么您无法成功解析20140231字符串的原因。

You can clearly get the last day of February like; 您可以像这样清楚地获得2月的最后一天:

DateTime lastDayOfFebruary = (new DateTime(2014, 2, 1)).AddMonths(1).AddDays(-1);

If your service always get year as a first 4 character, you can use .Substring() to get year and pass DateTime constructor as a year. 如果您的服务始终以第一个4个字符作为年份,则可以使用.Substring()获取年份,并将DateTime构造函数作为年份传递。

var date = "20140231";
string year = date.Substring(0, 4);
DateTime lastDayOfFebruary = (new DateTime(int.Parse(year), 2, 1)).AddMonths(1).AddDays(-1);

You could create a while , cut the date in pieces, and keep subtracting one from the day part until it is a valid date. 您可以创建while ,将日期分割成几部分,并继续从日部分中减去一个,直到它是有效日期为止。 This should really be fixed on the entry side though. 这实际上应该在入口端固定。

Try this: 尝试这个:

var date = "20140231";
DateTime scope;
bool dateValid = DateTime.TryParseExact(date, "yyyyMMdd", CultureInfo.CurrentCulture, DateTimeStyles.None, out scope);

while (!dateValid)
{
    string yearMonth = date.Substring(0, 4);
    int day = Convert.ToInt32(date.Substring(6, 2));

    if (day > 1)
    {
        day--;
    }
    else
    {
        break;
    }

    date = yearMonth + day.ToString().PadLeft(2, '0');

    dateValid = DateTime.TryParseExact(date, "yyyyMMdd", CultureInfo.CurrentCulture, DateTimeStyles.None, out scope);
}

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

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