views:

91

answers:

3

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!

+2  A: 
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:

Timwi
I actually wouldn't take it as an integer when it is read from an csv (text) and formatted like a date without separators. I would directly parse it from the string.
Stefan Steinegger
+5  A: 

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.

Kobi
A: 

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..

Raze2dust
Discarding the result of `Insert`.
Timwi
still isn't hot - `dateString` is an `int`, and `l` should be an `int`. It is generally better to run the code first, make sure it works.
Kobi