DateTime解析包含一年中某一天的字符串

时间:2018-03-15 17:28:48

标签: c# parsing datetime

我试图解析一个格式如下的字符串:

1900-001T00:00:00Z

进入DateTime对象。那里的中间位(在" 1900 - &#34之后;在" T"之前)应该是一年中的一天。我知道我需要使用的其余格式字符串是

yyyy-XXXTHH:mm:ssZ

但我应该为此做些什么' XXX'?

3 个答案:

答案 0 :(得分:2)

自编写的解析器可能如下所示:

static DateTime ToDt(string date)
{
    var splitYear = date.Split(new[] { '-' }, StringSplitOptions.RemoveEmptyEntries);
    var splitDays = splitYear[1].Split(new[] { 'T' }, StringSplitOptions.RemoveEmptyEntries);
    var hms = splitDays[1].TrimEnd('Z').Split(':');

    var dt = new DateTime(int.Parse(splitYear[0]), 1, 1, 0, 0, 0);
    dt = dt.AddDays(int.Parse(splitDays[0]) - 1);
    dt = dt.AddHours(int.Parse(hms[0]));
    dt = dt.AddMinutes(int.Parse(hms[1]));
    dt = dt.AddSeconds(int.Parse(hms[2]));

    return dt;
}

static void Main(string[] args)
{
    Console.WriteLine(ToDt("1900-001T00:10:00Z"));
    Console.WriteLine(ToDt("1923-180T12:11:10Z"));
    Console.WriteLine(ToDt("1979-365T23:59:59Z"));
    Console.WriteLine(ToDt("2017-074T18:47:10Z"));


    Console.ReadLine();
}

输出:

01.01.1900 00:10:00
29.06.1923 12:11:10
31.12.1979 23:59:59
15.03.2017 18:47:10

如果

,这将抛出
  • 拆分未返回预期的拆分量(格式错误) IndexOutOfRangeException
  • 数字无法解析为 FormatException

和int不会防范“荒谬但信息良好”的输入

'2000-999T99:99:99Z'   -->  29.09.2002 04:40:39

答案 1 :(得分:2)

我确信有更好的方式,但你可以编写自己的方法来做到这一点:

oneRepMax

答案 2 :(得分:1)

基于@AlexK的建议,你走了,好看又简单......

using System.Globalization;
using System.Text.RegularExpressions;

    private DateTime? ParseDayOfYearDate(string value)
    {
        DateTime? result = null;
        Regex dayOfYearDatePattern = new Regex(@"^(\d+\-)(\d+)(.+)$");
        Match dayOfYearDateMatch = dayOfYearDatePattern.Match(value);
        if (dayOfYearDateMatch.Success)
        {
            string altered = dayOfYearDateMatch.Groups[1].Value + "01-01" + dayOfYearDateMatch.Groups[3].Value;
            int dayOfYear = int.Parse(dayOfYearDateMatch.Groups[2].Value); // will succeed due to the definition of the pattern
            DateTime startOfYear = DateTime.ParseExact(altered, "yyyy-MM-ddTHH:mm:ssK", CultureInfo.InvariantCulture, DateTimeStyles.RoundtripKind);
            result = startOfYear.AddDays(dayOfYear - 1); // since we already gave it 1st January
        }
        else
        {
            // It didn't match the pattern, will return null.
        }

        return result;
    }