Margus
Margus

Reputation: 20058

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. What is the cleanest way to get last date of February with input of "20140231"?

There is 1 constraint - this should work with .net 2.0.

Upvotes: 0

Views: 1773

Answers (3)

Soner Gönül
Soner Gönül

Reputation: 98848

February can have only 28 or 29 days depends on current year is a leap year or not.

It can't have 30 or 31 days in any year. That's why you can't parse your 20140231 string successfully.

You can clearly get the last day of February like;

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.

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

Upvotes: 5

Alan H
Alan H

Reputation: 262

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

Upvotes: 14

Patrick Hofman
Patrick Hofman

Reputation: 157098

You could create a while, cut the date in pieces, and keep subtracting one from the day part until it is a valid date. 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);
}

Upvotes: 1

Related Questions