簡體   English   中英

字符串未被識別為有效的日期時間。 即使使用 parse Exact

[英]string was not recognized as a valid DateTime. even if using parse Exact

我正在使用 parse exactl 來轉換以下字符串,但仍然給我一個錯誤:

Tue Oct 06 2020 15:22:59 GMT 0200 (Central European Summer Time)

這是我的轉換:

  DateTime frm = DateTime.ParseExact(dtFrom, "yyyy/MM/dd", CultureInfo.InvariantCulture);

使用正則表達式:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            string input = "Tue Oct 06 2020 15:22:59 GMT 0200 (Central European Summer Time)";
            string pattern = @"^(?'date'.*)(?'sign'.)(?'offset'\d{4})\s(?'ending'\([^)]+\))$";
            Match match = Regex.Match(input, pattern);
            string dateStr = match.Groups["date"].Value;
            string sign = match.Groups["sign"].Value;
            string offset = match.Groups["offset"].Value;
            switch (sign)
            {
                case " ":
                    dateStr = dateStr + " +" + offset;
                    break;
                case "+":
                    dateStr = dateStr + sign + offset;
                    break;
                case "-":
                    dateStr = dateStr + sign + offset;
                    break;
            }
            DateTime date = DateTime.ParseExact(dateStr,"ddd MMM dd yyyy HH:mm:ss \\G\\M\\T zzz", System.Globalization.CultureInfo.InvariantCulture);
        }

    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM