C#解析UTC日期时间 [英] c# Parsing UTC datetime

查看:222
本文介绍了C#解析UTC日期时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图解析11/23/2011 23点59分59秒UTC +0800为C#DateTime对象,但在尝试为标准的DATETIME解析方法,甚至日期时间确切的分析,我得到无效的日期。

I am trying to parse 11/23/2011 23:59:59 UTC +0800 as a c# datetime object but trying the standard datetime parse method or even the datetime exact parse I get invalid date.

任何想法?

推荐答案

我会建议你解析到的DateTimeOffset ,而不是的DateTime 在格式字符串中使用时区偏移量说明时,建议在MSDN:

I would suggest you parse to a DateTimeOffset instead of a DateTime, as recommended in MSDN when using a time zone offset specifier in the format string:

using System;
using System.Globalization;

class Test
{    
    static void Main(string[] args)
    {
        string text = "11/23/2011 23:59:59 UTC +0800";
        string pattern = "MM/dd/yyyy HH:mm:ss 'UTC' zzz";

        DateTimeOffset dto = DateTimeOffset.ParseExact
            (text, pattern, CultureInfo.InvariantCulture);
        Console.WriteLine(dto);
    }
}



然后,您可以将其转换为日期时间在UTC值,如果你想要的,但有没有这样的事情为的DateTime 以8小时偏移 - 一个的DateTime 是被视为普遍的,本地或指定,无处为特定偏移被储存。

You can then convert that to a DateTime value in UTC if you want, but there's no such thing as "a DateTime with an offset of 8 hours" - a DateTime is either regarded as universal, local or unspecified, with nowhere for a specific offset to be stored.

的DateTime 是在好奇类型各种方式的,并可能导致粗心的开发问题。

DateTime is a curious type in various ways, and can cause problems for the unwary developer.

这篇关于C#解析UTC日期时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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