I need to parse a date string which could be in any reasonable format. For example:
2012-12-25
25 december 2012
25 dec
17:35
Some of these strings contain ambiguous dates which can result in several possible DateTime
values (E.g. 25 dec
can be interpreted as 2012-12-25
, 2011-12-25
, 1066-12-25
, etc).
The way DateTime.Parse
currently handles these ambiguous values is by using the current system date to determine the context. So if the current date is 26th July 2012 the string 25 dec
is assumed to be in the current year and is parsed as 2012-12-25
Is it somehow possible to change this behaviour and set the current date context myself?
The only thing I can think of is post processing the date. You have the string afterwards and you have the year in the DateTime object. If the string does not contain the year then set the year yourself.
if(! string.contains(DateTime.Year.toString() ) {
// Set the year yourself
}
If you expect to get "incomplete" date/time information in various formats, you could try parsing the text as specific different formats least-detailed to most-detailed. For example:
var text = "June 15";
DateTime datetime;
if(DateTime.TryParseExact(text, "m", CultureInfo.CurrentCulture, DateTimeStyles.AssumeLocal, out datetime))
{
// was just month, day, replace year with specific value:
datetime = new DateTime(1966, datetime.Month, datetime.Day);
}
else
{
// wasn't just month, day, try parsing a "whole" date/time:
datetime = DateTime.Parse(text);
}
...this code tries to parse month/day format in the current culture (if you have a specific one, independent of current culture, you can replace "CultureInfo.CurrentCulture" with a culture that has the format you want). If that fails, it assumes the text is more detailed and goes on to parse it as you normally would.
If your date/times are not local, don't use DateTimeStyles.AssumeLocal
. I always recommend that date/time data that is stored in any way (like serialized to text) that you always use Universal; because you don't know what culture was in play when the data was serialized. Universal is the only reliable way to get date/time data on level playing field. In which case use DateTimeStyles.AssumeUnivesal
.
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