c# Parsing UTC datetime

2019-01-24 01:38发布

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.

Any ideas?

4条回答
干净又极端
2楼-- · 2019-01-24 01:52

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

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 is a curious type in various ways, and can cause problems for the unwary developer.

查看更多
干净又极端
3楼-- · 2019-01-24 01:53

Msdn for Format settings: https://msdn.microsoft.com/en-us/library/az4se3k1(v=vs.110).aspx

public class Program
{
    public static void Main()
    {
         //original date
        string _date = "Thu Jan 15 11:32:09 +0200 2015";
         // Describes the date format
        string _parsePattern = "ffffd MMM dd HH:mm:ss zzz yyyy"; 

         DateTimeOffset dto = DateTimeOffset.ParseExact(_date, _parsePattern, CultureInfo.InvariantCulture);

         //last settings
        Console.WriteLine(dto.ToString("dd.MM.yyyy hh:mm:ss",CultureInfo.CreateSpecificCulture("tr-TR")));
    }
}

for extension method:

public static DateTime getDateFromFormat(this string _date, string _parsePattern)
        {
            DateTimeOffset dto = DateTimeOffset.ParseExact(_date, _parsePattern, CultureInfo.InvariantCulture);
            return Convert.ToDateTime(dto.ToLocalTime());
        }

For test: https://dotnetfiddle.net/xdnjGy

查看更多
够拽才男人
4楼-- · 2019-01-24 01:55
We Are One
5楼-- · 2019-01-24 02:07

As written by James, you can try

var dt = DateTime.ParseExact(
         "11/23/2011 23:59:59 UTC +0800", 
         "MM/dd/yyyy HH:mm:ss 'UTC' K", 
          CultureInfo.InvariantCulture);

You'll get a date in the "local" time.

查看更多
登录 后发表回答