将日期格式从 dd/MM/yyyy 转换为 MM/dd/yyyy

时间:2021-07-15 21:18:37

标签: c# datetime asp.net-core

在我们的网络应用程序中,我们支持西班牙语。在收集信息的过程中,我们允许用户以 dd/MM/yyyy 格式输入西班牙语版网站的日期,以及 MM/dd/yyyy 格式的网站英语版。

收集该信息后,我们将整个对象发送到微服务进行处理。在这里,我尝试将 dd/MM/yyyy 转换为 MM/dd/yyyy,然后再从我的 Web 应用程序发送信息。

我在将 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)日期转换为 Date 属性。

1 个答案:

答案 0 :(得分:1)

您的问题有些不清楚,但似乎 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);
}