How to convert string date without zero padding and delimiter to DateTime

This is a stupid question. but I have a date in a string without zero padding and any separator, for example:

string date = "2016111";

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

+4
source share
2 answers

In general, you cannot: your own example demonstrates this. Does it "2016111"matter

2016 Nov 1    // 2016-11-1

or

2016 Jan 11   // 2016-1-11

Technically, you can supply

  string date = "2016111";

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

And get

   1 Nov 2016
+7
source

, , .
, , .

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

    if (str.Length == 8)
    {
        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;
}
0

Source: https://habr.com/ru/post/1663600/


All Articles