Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert a string date without zero padding and separator to DateTime

Tags:

c#

.net

datetime

It's a stupid question. but I have date in a string without zero padding and any separator like following:

string date = "2016111";

Is there a way to convert it to date format using C# lib or any other way? I am not sure about last three digits, either last one digit - it can be day or the last two digits can be day.

like image 840
Ravi Anand Avatar asked Dec 13 '16 09:12

Ravi Anand


2 Answers

In general case, you can't: your own example demonstrates this. Does "2016111" mean

2016 Nov 1    // 2016-11-1

or

2016 Jan 11   // 2016-1-11

Technically, you can put

  string date = "2016111";

  var result = DateTime.ParseExact(date, 
    "yyyyMd", 
    CultureInfo.InvariantCulture, 
    DateTimeStyles.AssumeLocal);

And obtain

   1 Nov 2016
like image 98
Dmitry Bychenko Avatar answered Oct 02 '22 16:10

Dmitry Bychenko


As the others have said, you can't, sometimes you obtain two valid dates.
But maybe this approach can be useful for you.

public static List<DateTime> ParseAmbiguousDate(string str)
{
    var result = new List<DateTime>();
    DateTime d;

    if (str.Length == 8)
    {  
        //note that you have to change the format depending on your culture info
        if (DateTime.TryParseExact(str, "yyyyMMdd", CultureInfo.InvariantCulture, DateTimeStyles.AssumeLocal, out d))
        {
            result.Add(d);
            return result;
        }
    }
    else if (str.Length == 7)
    {
        var str1 = str.Insert(4, "0");
        if (DateTime.TryParseExact(str1, "yyyyMdd", CultureInfo.InvariantCulture, DateTimeStyles.AssumeLocal, out d))
        {
            result.Add(d);
        }

        var str2 = str.Insert(6, "0");
        if (DateTime.TryParseExact(str2, "yyyyMdd", CultureInfo.InvariantCulture, DateTimeStyles.AssumeLocal, out d))
        {
            result.Add(d);
        }
    }

    return result;
}
like image 20
Pedro Perez Avatar answered Oct 02 '22 14:10

Pedro Perez