3

I try to to convert string to specific datetime format.

I have string:

1431075600

and I try convert this by:

private static IFormatProvider culture = new System.Globalization.CultureInfo("en-GB");
model.DeliveryDate = DateTime.Parse(data.DeliveryDate, culture, System.Globalization.DateTimeStyles.AssumeLocal);

I got error message:

String was not recognized as a valid DateTime.

Finally I want to have datetime in format like

Friday, 8 May 2015 hour: 09:00
Mehrzad Chehraz
  • 5,092
  • 2
  • 17
  • 28
mskuratowski
  • 4,014
  • 15
  • 58
  • 109
  • 1
    What datetime format your input string is using? I assume it's Unix timestamp? Then you can find the answer there: http://stackoverflow.com/a/17632585/860913 – Aleksey Shubin Apr 26 '15 at 09:35

1 Answers1

3

Your string looks like a Unix Time which is elapsed as a seconds since 1 January 1970 00:00 UTC.. That's why, you can't directly parse it to DateTime. You need to create a unix time first and add this value as a second.

That's why you need to add your string as a second to this value like;

var dt = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
dt = dt.AddSeconds(1431075600).ToLocalTime();

And you can format your string after that with an english-based culture line InvariantCulture;

Console.WriteLine(dt.ToString("dddd, d MMM yyyy 'h'our: HH:mm",
                              CultureInfo.InvariantCulture));

Result will be;

Friday, 8 May 2015 hour: 09:00

Here a demonstration.

Soner Gönül
  • 97,193
  • 102
  • 206
  • 364