簡體   English   中英

在C#中將字符串dd-MM-yyyy轉換為DateTime yyyy-MM-dd

[英]Converting string dd-MM-yyyy to DateTime yyyy-MM-dd in C#

我有以下格式的字符串:

21‎-‎10‎-‎2014‎ ‎15‎:‎40‎:‎30

我想將其設置為DateTime格式:

2014-‎10‎-‎21 ‎15‎:‎40‎:‎30

我努力了:

DateTime dt = DateTime.ParseExact("21‎-‎10‎-‎2014‎ ‎15‎:‎40‎:‎30", "yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture);

但不走運,它會引發異常String was not recognized as a valid DateTime

編輯

我也嘗試過:

DateTime dt = DateTime.ParseExact("21-‎10‎-‎2014‎ ‎15‎:‎40‎:‎30", "dd-MM-yyyy HH:mm:ss", CultureInfo.InvariantCulture);

兩個參數的格式相同。 例外是相同的,因此問題不在於格式之間的差異。 我已經檢查過了。

輸入字符串包含從左到右的標記字符,您可以通過將其粘貼到支持Unicode的編輯器中並查看空白字符來看到它們。 另請參閱Ideone (僅在編輯模式下可見)。

整理輸入內容

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

public class Test
{
    public static void Main()
    {
        string dateTimeString = "21‎-‎10‎-‎2014‎ ‎15‎:‎40‎:‎30";
        dateTimeString = Regex.Replace(dateTimeString, @"[^\u0000-\u007F]", string.Empty);

        string inputFormat = "dd-MM-yyyy HH:mm:ss";
        string outputFormat = "yyyy-MM-dd HH:mm:ss";
        var dateTime = DateTime.ParseExact(dateTimeString, inputFormat, CultureInfo.InvariantCulture);
        string output = dateTime.ToString(outputFormat);

        Console.WriteLine(output);
    }
}

輸出:

2014-10-21 15:40:30

暫無
暫無

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

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