![](/img/trans.png)
[英]How to change date format from DD/MM/YYYY or MM/DD/YYYY to YYYY-MM-DD?
[英]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.