Any ideas? I can't come up with any.
I have a list of dates I'm loading in from a csv file and they are saved as all integers, or rather a string of integers (i.e. Jan 1, 2009 = 1012009)
Any ideas on how to turn 1012009 into 1/01/2009?
Thanks!
Any ideas? I can't come up with any.
I have a list of dates I'm loading in from a csv file and they are saved as all integers, or rather a string of integers (i.e. Jan 1, 2009 = 1012009)
Any ideas on how to turn 1012009 into 1/01/2009?
Thanks!
int date = 1012009;
var month = date / 1000000;
var day = (date / 10000) % 100;
var year = date % 10000;
var formatted = new DateTime(year, month, day).ToString();
This assumes month-day-year; if the numbers are day-month-year, I’m sure you’ll be able to swap the month and day variables to accommodate that.
If you want to customise the date format, you can do so as described in:
Since the date is stored as a string, you may want to use ParseExact
:
DateTime date = DateTime.ParseExact("28012009", "dMMyyyy", null);
ParseExact
will throw an exception if the format doesn't match. It has other overloads, where you can specify more than a single possible format, if that is required. Note that here provider
is null
, which uses the current culture.
Depending on style you may wish to use TryParseExact
.
Let 10102009 be dateInt.
string dateString = dateInt.ToString();
int l = dateString.Length;
dateString = dateString.Insert(l-3,"/");
dateString = dateString.Insert(l-6,"/");
You should now have 1/01/2009 in dateString.. You can also try the ParseExact function..