Search code examples
c#jsondatedatetimeutc

Convert 2015-06-01T02:31:00+0000 to DateTime object c#


I'm writting an app that consume this webservice:

http://finance.yahoo.com/webservice/v1/symbols/allcurrencies/quote?format=json

as you can see there, the JSON object comes with an utc datetime field. I want to save this information in a simple DateTime object with the following format "yyyy-MM-dd HH:mm:ss".

This is my code:

 DateTime dateParsed = DateTime.Now;       
 DateTime.TryParseExact((string)resource.SelectToken("resource").SelectToken("fields")["utctime"], "yyyy'-'MM'-'dd'T'HH':'mm':'ssz", CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.AdjustToUniversal, out dateParsed);

I'm getting an DateTime object initialized in the year 0001.

What I'm doing wrong?


Solution

  • You have just an error in your Format-String. This is a working sample:

    using System;
    using System.Globalization;
    
    public class Program
    {
        public static void Main()
        {
            DateTime dateParsed = DateTime.Now; 
            if ( DateTime.TryParseExact( "2015-06-01T02:31:00+0000", "yyyy-MM-ddThh:mm:ss+0000", CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.AdjustToUniversal, out dateParsed ) ) {
                Console.WriteLine(string.Format("Parsing done: {0:MM/dd/yyyy @ hh:mm}", dateParsed ) );
            } else {
                Console.WriteLine("No result");
            }
        }
    }
    

    Note: the +0000 is hardcoded, when you get other values you would need to detect them. If the api returns only +0 values, you could cut them off and work without z.