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.
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
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With