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

喜夏-厌秋 提交于 2020-06-29 05:03:10

问题


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?


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/30565262/convert-2015-06-01t0231000000-to-datetime-object-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!