簡體   English   中英

將日期格式從 dd/MM/yyyy 轉換為 MM/dd/yyyy

[英]Converting Date format from dd/MM/yyyy to MM/dd/yyyy

在我們的 Web 應用程序中,我們支持西班牙語。 在收集信息時,我們允許用戶以 dd/MM/yyyy 格式輸入西班牙版網站的日期和 MM/dd/yyyy 格式的網站英文版。

在收集到這些信息后,我們將整個對象發送到微服務進行處理。 在這里,我試圖在從我的 Web 應用程序發送信息之前將 dd/MM/yyyy 轉換為 MM/dd/yyyy。

我在將 dd/MM/yyyy 轉換為 MM/dd/yyyy 時遇到問題。

我遵循的步驟轉換格式:

用戶輸入:26/02/2020

string effDate = effectivePolicyDate.ToString("MM/dd/yyyy", CultureInfo.CreateSpecificCulture("en-US"));

EffectivePolicyDate 是用戶輸入。 從上面的代碼,我得到 effDate = "02/26/2020"(在字符串中得到預期的結果。)

我需要以 DateTime 格式而不是字符串發送日期,因此嘗試將其轉換為下面的 DateTime。

var date = DateTime.ParseExact(effDate, "MM/dd/yyyy", CultureInfo.InstalledUICulture);

在這里,我試圖解析日期,在我收到 26/02/2020(dd/MM/yyyy) 但不是 MM/dd/yyyy 的日期。

var date2 = DateTime.Parse(effDate);

上面的行拋出異常。

DateTime.Parse("2/26/2021");
'DateTime.Parse("2/26/2021")' threw an exception of type 'System.FormatException'
    Data: {System.Collections.ListDictionaryInternal}
    HResult: -2146233033
    HelpLink: null
    InnerException: null
    Message: "String '2/26/2021' was not recognized as a valid DateTime."
    Source: "System.Private.CoreLib"
    StackTrace: "   at System.DateTimeParse.Parse(ReadOnlySpan`1 s, DateTimeFormatInfo dtfi, DateTimeStyles styles)\r\n   at System.DateTime.Parse(String s)"
    TargetSite: {System.DateTime Parse(System.ReadOnlySpan`1[System.Char], System.Globalization.DateTimeFormatInfo, System.Globalization.DateTimeStyles)}
DateTime.Parse("26/2/2021");

我沒有找到將日期格式從 dd/MM/yyyy 轉換為 MM/dd/yyyy 的方法,我按原樣發送了日期和其他應用程序處理。 我很想知道是否可以轉換格式。 我成功轉換為字符串,但未能將字符串(MM/dd/yyyy)日期轉換為日期屬性。

你的問題有點不清楚,但似乎var date2 = DateTime.Parse(effDate); 是問題。 我在下面的測試中添加了兩個使用DateTime.Parse例子,我希望這會有所幫助。

[Test]
public void DateTests()
{
    var expectedDate = new DateTime(2020, 2, 26);

    var date1 = DateTime.Parse("2/26/2020", new CultureInfo("en-US"));
    Assert.AreEqual(expectedDate, date1);

    var date2 = DateTime.Parse("26/2/2020", new CultureInfo("es-ES"));
    Assert.AreEqual(expectedDate, date2);
}

暫無
暫無

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

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