0

I'm trying to convert the DateTime in UTC format to a locale of my choice.

For example, 08.09.2016 17:34:33Z should convert to 08.09.2016 11:34:33 if the locale is set to es-CL.

My code:

    public static void Main(string[] args)
    {
          CultureInfo en = new CultureInfo("es-CL");
          Thread.CurrentThread.CurrentCulture = en;

          // Creates a DateTime for the local time.
          string activityTime = "08.09.2016 17:34:33Z";

          DateTime dt = DateTime.Parse(activityTime);

          // Converts the local DateTime to the UTC time.
          DateTime utcdt = dt.ToUniversalTime();
          Console.WriteLine("utc time: " + utcdt.ToString());

          // Defines a custom string format to display the DateTime value.
          // zzzz specifies the full time zone offset.
          String format = "dd/MM/yyyy hh:mm:sszzz";

          // Converts the local DateTime to a string 
          String str = dt.ToString(format);
          Console.WriteLine(str);

          // Converts the UTC DateTime to a string 
          String utcstr = utcdt.ToString(format);
          Console.WriteLine(utcstr);

          // Converts the string back to a local DateTime and displays it.
          DateTime parsedBack = DateTime.ParseExact(str,format,en.DateTimeFormat);
          Console.WriteLine("local time: " + parsedBack);

          DateTime parsedBackUTC = DateTime.ParseExact(str,format, en.DateTimeFormat, DateTimeStyles.AdjustToUniversal);
          Console.WriteLine(parsedBackUTC);
    }

My output:

utc time: 08-09-2016 17:34:33
08-09-2016 07:34:33+02:00
08-09-2016 05:34:33+02:00
local time: 08-09-2016 7:34:33
08-09-2016 5:34:33

What am I doing incorrectly?

Bhav
  • 1,957
  • 7
  • 33
  • 66
  • There are two parts to this: a) converting between local time and UTC; b) parsing/formatting. You should separate those concerns, dealing with one of them at a time. – Jon Skeet Sep 09 '16 at 15:17
  • 1
    Wouldn't it be easier to use [TimeZoneInfo.ConvertTime](https://msdn.microsoft.com/en-us/library/bb382770(v=vs.110).aspx)? – stuartd Sep 09 '16 at 15:18
  • Similar to http://stackoverflow.com/questions/20776093, but the key is that there's not a 1:1 relationship between _culture_ and _time zone_. e.g. the US has 6 time zones, and Chile has two (although one of them is only for Easter Island). – D Stanley Sep 09 '16 at 15:18
  • What's about reading [Converting Times Between Time Zones](https://msdn.microsoft.com/en-us/library/bb397769(v=vs.110).aspx?cs-save-lang=1&cs-lang=csharp#code-snippet-7)? – help-info.de Sep 09 '16 at 15:22

0 Answers0