如何知道一个给定的字符串是否是有效的UTC DateTime格式? [英] How to know whether a given string is a valid UTC DateTime format?

查看:2265
本文介绍了如何知道一个给定的字符串是否是有效的UTC DateTime格式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要让接受UTC日期时间: http://www.w3.org/ TR / NOTE-日期时间

I'd need to allow accepting UTC datetimes: http://www.w3.org/TR/NOTE-datetime

如:

 - Year:
         YYYY (eg 1997)    Year and month:
         YYYY-MM (eg 1997-07)    Complete date:
         YYYY-MM-DD (eg 1997-07-16)    Complete date plus hours and minutes:
         YYYY-MM-DDThh:mmTZD (eg 1997-07-16T19:20+01:00)    Complete date plus hours, minutes and seconds:
         YYYY-MM-DDThh:mm:ssTZD (eg 1997-07-16T19:20:30+01:00)    Complete date plus hours, minutes, seconds and a decimal fraction of
   a second
         YYYY-MM-DDThh:mm:ss.sTZD (eg 1997-07-16T19:20:30.45+01:00) where:

        YYYY = four-digit year
        MM   = two-digit month (01=January, etc.)
        DD   = two-digit day of month (01 through 31)
        hh   = two digits of hour (00 through 23) (am/pm NOT allowed)
        mm   = two digits of minute (00 through 59)
        ss   = two digits of second (00 through 59)
        s    = one or more digits representing a decimal fraction of a second
        TZD  = time zone designator (Z or +hh:mm or -hh:mm)

如何将字符串转换为datetime具有特定的格式?

How to Convert a string to a DateTime with a specific format?

我写了下面的code:

I wrote the below code:

 private const string Format = "YYYY-MM-DDThh:mm:ssZ";

        public DateTime? Parse(string modifiedSince)
        {
            // how to know whether it's a valid DateTime in UTC format?
        }

但它始终返回null,这意味着它不能解析到日期时间。

But it always returns null which means that it fails to parse to DateTime.

应该成功验证下面UTC值,但它不会:

It should successfully validate below UTC values but it doesn't:

2013-05-10
2013-05-10T05:04:10
2013-05-10T05:04:10.40
013-05-10T05:04:10.4Z

(Z是可选的通常情况下)

(Z is optional usually)

如何使用DateTime.Parse或.Parsexact,使其成功返回的日期为上述格式?

How to use DateTime.Parse or .Parsexact so that it successfully returns a date for the above format?

所有其他日期格式应该如失败20130510

All other date formats should fail e.g. 20130510

我可以写一个正则表达式呢?

I could write a Regex instead?

推荐答案

您缺少一些重要的东西。 UTC不是的格式

You are missing something important. UTC is not a format.

UTC指的是协调世界时(是的,缩写是失序的故意)。这是在本初子午线的固定时钟,相当于GMT所有的实际目的。它不为夏令时间或夏时制改变,而且是我们谈论的其他时区偏移时放置为零。

UTC refers to "Coordinated Universal Time" (yes, the abbreviation is out of sequence intentionally). This is a fixed clock at the prime meridian, equivalent to GMT for all practical purposes. It does not change for "daylight savings time" or "summer time", and it is where we place the zero when talking about offsets of other time zones.

你所描述的格式被称为 ISO8601 。技术上,ISO8601标准定义的若干个的格式,而是最常用的是还的 RFC3339 并只覆盖了最后你们两个列出的格式。换句话说,ISO8601允许的时间多次重新presentations不同precisions,但RFC3339要求值到的第二

The format you are describing is known as ISO8601. Technically, the ISO8601 standard defines several formats, but the one most commonly used is also defined in RFC3339 and covers only the last two of the formats you listed. In other words, ISO8601 allows multiple representations of time at different precisions, but RFC3339 requires values up to the second.

现在,当涉及到.NET,你缺少另一对夫妇的重要概念。具体来说,您需要注意的 DateTime.Kind 的DateTimeOffset <的/ STRONG>

Now when it comes to .Net, you are missing another couple of important concepts. Specifically, you need to be aware of DateTime.Kind and DateTimeOffset.

当你有一个包含以Z +00的字符串值:00 结尾,你就知道它重新presents时间UTC,并且可以存储在的DateTime DateTime.Kind == DateTimeKind.Utc

When you have a string value that includes a Z or +00:00 at the end, you know that it represents time at UTC, and can be stored in a DateTime that has DateTime.Kind == DateTimeKind.Utc.

如果你有一些其他的抵消,如 +01:00 -04:00 ,那么你应在的DateTimeOffset 对象,而不是来存储这些。如果试图将其存储在一个的DateTime ,那么你必须选择是否要忽略的偏移量,或应用它,保存时间为UTC。

If you have some other offset, such as +01:00 or -04:00, then you should be storing these in a DateTimeOffset object instead. If you try to store it in a DateTime, then you have to choose whether you are going to ignore the offset, or apply it and store the time as UTC.

如果你没有的末任何的,那么你有歧义。您可以存储这个在的DateTime ,其中 Datetime.Kind == DateTimeKind.Unspecified ,但你必须非常小心什么你用它做。它没有什么时区的任何信息或偏移值源于 - 因此,任何数学运算可能不正确。例如,您应该的从不的获得通过减去持续时间两个的DateTime 与指定(或本地)种valules。有关详细信息,请参见这个博客帖子

If you don't have anything at the end, then you have ambiguity. You can store this in a DateTime where Datetime.Kind == DateTimeKind.Unspecified but you must be very careful with what you do with it. It doesn't have any information about what time zone or offset that value originated from - so any math operations might be incorrect. For example, you should never obtain a duration by subtracting two DateTime valules with unspecified (or local) kinds. For additional details, see this blog post.

最后一件事,明白净有没有内置类,再presents没有时间约会。为此,我们通常使用的DateTime 在午夜 - 但你不能从您在午夜实际上给出的时间的值区分这一点。在其他更糟糕,解析后 2013年5月10日 2013-05-10T00:00:00 - 他们是等价的。

One last thing, understand that .Net has no built-in class that represents a date without a time. For that, we commonly use a DateTime at midnight - but you would not be able to distinguish this from a value where you were actually given the time at midnight. In other worse, after parsing 2013-05-10 and 2013-05-10T00:00:00 - they are equivalent.

下面是一些code,让你开始。

Here is some code to get you started.

public DateTime? Parse(string s)
{
    // you may want to add a few more formats here
    var formats = new[] { "yyyy-MM-dd",
                          "yyyy-MM-ddThh:mm:ss",
                          "yyyy-MM-ddThh:mm:ssZ" };

    DateTime dt;
    if (DateTime.TryParseExact(s, formats,
                               CultureInfo.InvariantCulture, // ISO is invariant
                               DateTimeStyles.RoundtripKind, // this is important
                               out dt))
        return dt;

    return null;
}

您也应该看看 DateTimeOffset.TryParseExact 如果你打算走这路线。

You should also look into DateTimeOffset.TryParseExact if you plan to go down that route.

这篇关于如何知道一个给定的字符串是否是有效的UTC DateTime格式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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