开发者

How to convert a date of integers to a formated date string (i.e. 2012009 to 2/01/2009)

Any ideas? I can't come up with any.

I have a list of da开发者_如何学运维tes 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!


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.


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:

  • Standard Date and Time Format Strings
  • Custom Date and Time Format Strings


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜