将2015-06-01T02:31:00 + 0000转换为DateTime对象c# [英] Convert 2015-06-01T02:31:00+0000 to DateTime object c#

查看:53
本文介绍了将2015-06-01T02:31:00 + 0000转换为DateTime对象c#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm writting an app that consume this webservice:

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

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

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".

这是我的代码:

 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对象。

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

我在做什么错了?

推荐答案

您的Format-String中只有一个错误。这是一个工作示例:

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

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

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.

这篇关于将2015-06-01T02:31:00 + 0000转换为DateTime对象c#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆