none
Issue with DateTime parsing RRS feed

  • Question

  • Hello,

    When I try to parse the "2017-09-25T11:06:55+00:00" date string using TryParse method, I get the following output: {9/25/2017 7:06:55 AM}
    So looks like 11am is getting converted into 7am.Not sure why is this happening so?Is it because of +00:00?? What do I need to do so that parsed Datetime output is same: i.e. {9/25/2017 11:06:55 AM} ?
    I tried using Current culture and DateTimeStyles.AssumeLocal but no luck. (Note: I'm in the eastern time-zone)

    Thanks.

    Friday, October 6, 2017 6:21 PM

Answers

  • The following returns me the required format. Use the value of dateOutput.

    string value = "2017-09-25T11:06:55+00:00";
    DateTime dateOutput = DateTimeOffset.Parse(value).DateTime;


    Thanks, AT

    Friday, October 6, 2017 6:57 PM

All replies

  • If you call DateTime.Parse like this:  DateTime.Parse("2017-09-25T11:06:55+00:00");

    You will create a local DateTime (DateTime.Kind==Local).  Because of the +00:00, the DateTime parser knows that the string you provided is actually given in UTC time though.  So it takes 11 AM UTC, and converts that to local time (7 AM EDT).

    It sounds like you really want to do more like this:

    var dt = DateTime.Parse("2017-09-25T11:06:55+00:00").ToUniversalTime();


    Friday, October 6, 2017 6:53 PM
  • The following returns me the required format. Use the value of dateOutput.

    string value = "2017-09-25T11:06:55+00:00";
    DateTime dateOutput = DateTimeOffset.Parse(value).DateTime;


    Thanks, AT

    Friday, October 6, 2017 6:57 PM
  • Try this too:

    string s = "2017-09-25T11:06:55+00:00";
    DateTime utc_time = DateTime.ParseExact( s, "yyyy'-'MM'-'dd'T'HH':'mm':'ssK", CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal );
    DateTime local_time_on_this_machine = utc_time.ToLocalTime();
    
    Console.WriteLine( utc_time );
    Console.WriteLine( utc_time.Kind );
    Console.WriteLine( local_time_on_this_machine );
    Console.WriteLine( local_time_on_this_machine.Kind );
    Console.WriteLine( local_time_on_this_machine.ToUniversalTime() );
    

    • Proposed as answer by Fei HuModerator Wednesday, October 11, 2017 11:37 AM
    Friday, October 6, 2017 7:03 PM