繁体   English   中英

DateTime解析C#

[英]DateTime parsing C#

我不能解析这个日期,怎么了?

 "Jul 15 2015 16: +0" 

+ 0的UTC附加时间,我想让时间以秒为单位。

世界标准时间

Console.WriteLine("Date: {0}", 
    DateTime.ParseExact("Jul 15 2015 16: +0", 
    "MMM dd yyyy HH", CultureInfo.InvariantCulture).ToString("MMM dd, yyyy"));

错误:

字符串未被识别为有效的DateTime

完整代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Globalization;

namespace ConsoleApplication3
{
    class Program
    {
        static void Main(string[] args)
        {
            string json = "{\"success\":true,\"price_prefix\":\"\",\"price_suffix\":\" pСѓР±.\",\"prices\":[[\"Jul 15 2015 16: +0\",1.745,\"6\"],[\"Jul 15 2015 17: +0\",1.78,\"5\"],[\"Jul 15 2015 18: +0\",1.65,\"7\"]]}";
            var prices = JObject.Parse(json)["prices"].Children()
                            .Select(j => new PriceItem
                            {
                                Date = (string)j[0],
                                Price = (float)j[1],
                                Count = (int)j[2]
                            });
            foreach (PriceItem priceItem in prices)
            {
                Console.WriteLine("Date: {0}", DateTime.ParseExact(priceItem.Date, "MMM dd yyyy HH", CultureInfo.InvariantCulture).ToString("MMM dd, yyyy"));
                Console.WriteLine("Price: {0}", priceItem.Price);
                Console.WriteLine("Count: {0}", priceItem.Count);
                Console.WriteLine(new string('-', 10));
            }   
            Console.ReadKey(true);
        }
    }

    class PriceItem
    {
        public string Date { get; set; }
        public float Price { get; set; }
        public int Count { get; set; }
    }
}

DateTime.ParseExact就是这样做的,它精确地解析输入数据。 如果输入数据不匹配,它将抛出异常(尽管有一个类似的函数DateTime.TryParseExact不会抛出)。

您输入的数据为Jul 15 2015 16: +0 ,其中包括时区和分隔符。 您想创建一个与之完全匹配的格式字符串,因此需要使用MMM dd yyyy HH':' z 冒号位于'标记内,因为解析器将其解释为时间分隔符,因此您需要告诉格式化程序从输入字符串中“将其作为文字复制”。

您的代码将变为:

Console.WriteLine("Date: {0}", 
    DateTime.ParseExact("Jul 15 2015 16: +0", 
    "MMM dd yyyy HH':' z", CultureInfo.InvariantCulture).ToString("MMM dd, yyyy"));

那应该起作用。

有关更多信息,请参见自定义DateTime格式字符串(MSDN)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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