Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert string to local Date Time?

I am trying to convert a string of this format:

MM/dd/yyyy HH:mm

The input is from a US database, so, i.e.: 09/20/2010 14:30

I know that my string is always US time but when I display it, I need to translate that into the local time, so that string should be turned into:

09/20/2010 19:30 (for UK for instance)

I tried a few things but nothing seems to give me the correct solution when I run on a US machine vs a UK or Ge machine I tried:

CompletedDttm = DateTime.ParseExact(value, "MM/dd/yyyy HH:mm", CultureInfo.CurrentCulture);
CompletedDttm = DateTime.ParseExact(value, "MM/dd/yyyy HH:mm", new CultureInfo("en-US"));

They all work locally (US machine) but they don't convert the time to local time on a European machine.

Thanks Tony

like image 797
tony Avatar asked Feb 26 '23 02:02

tony


1 Answers

Try this - it converts local time (input in US format) to GMT and then prints in GB/DE format.

var zones = TimeZoneInfo.GetSystemTimeZones();    // retrieve timezone info
string value = "09/20/2010 14:30";

DateTime CompletedDttm = DateTime.ParseExact(value, "MM/dd/yyyy HH:mm",    
    new CultureInfo("en-US"));
DateTime FinalDttm = TimeZoneInfo.ConvertTime(CompletedDttm, 
    TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time"), 
    TimeZoneInfo.FindSystemTimeZoneById("GMT Standard Time"));
string output = FinalDttm.ToString(new CultureInfo("en-GB"));

FinalDttm = TimeZoneInfo.ConvertTime(CompletedDttm, TimeZoneInfo.Local, 
    TimeZoneInfo.FindSystemTimeZoneById("W. Europe Standard Time"));
output = FinalDttm.ToString(new CultureInfo("de-DE"));

Output is, in turn:

20/09/2010 19:30:00

20.09.2010 20:30:00

like image 124
Steve Townsend Avatar answered Feb 28 '23 16:02

Steve Townsend