将2015-06-01T02:31:00 + 0000转换为DateTime对象c#

问题描述 投票:0回答:2

我正在编写使用此Web服务的应用程序:

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

如您所见,JSON对象带有utc datetime字段。我想将此信息以以下格式“ yyyy-MM-dd HH:mm:ss”保存在简单的DateTime对象中。

这是我的代码:

 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);

我正在从0001年初始化一个DateTime对象。

我做错了什么?

c# json date datetime utc
2个回答
3
投票

您的格式字符串中只有一个错误。这是一个工作示例:

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");
        }
    }
}

注意:+0000是硬编码的,当您获得其他值时,您将需要检测它们。如果api仅返回+0值,则可以将其切断并在没有z的情况下工作。


6
投票

您应该使用the K custom format specifier(而不是K)。

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); 作为偏移量。然后,通过使用+0000样式,所得的AdjustToUniversal将根据世界时表示为DateTime而且,由于您正在从已知的数据源中读取数据,因此使用DateTimeKind.Utc并没有真正的好处。数据源中的格式是固定的,因此只需将TryParseExact与该格式一起使用。 ParseExact方法主要用于验证用户输入或当源格式可能变化时。

最后一点-如果您仅使用Try...解析数据,则应自动识别该格式。您只需要使用JSON.netDateTime属性,它就可以毫无问题地对其进行解析。

© www.soinside.com 2019 - 2024. All rights reserved.