简体   繁体   中英

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?

You should be using the K custom format specifier (instead of z ).

string s = "2015-06-01T04:41:10+0000";

DateTime dt = DateTime.ParseExact(s, "yyyy-MM-dd'T'HH:mm:ssK",
                                  CultureInfo.InvariantCulture,
                                  DateTimeStyles.AdjustToUniversal);

It will read the +0000 as the offset. Then by using the AdjustToUniversal style, the resulting DateTime will also be in terms of Universal time, having DateTimeKind.Utc .

Also, since you're reading from a known data source, there's no real benefit of using TryParseExact . The format from your data source is fixed, so just use ParseExact with that format. The Try... methods are primarily for validating user input, or when the source format could vary.

One last point - if you just parse your data using JSON.net , that format should automatically be recognized. You just use a DateTime or DateTimeOffset property, and it would parse it without issue.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM