DateTime.Parse,拉脱维亚文化设置

发布于 2024-10-05 09:20:42 字数 734 浏览 0 评论 0原文

我发送的是 dd/MM/yyyy 格式的字符串,然后根据 web.config 全球化设置将其解析为 lv-LV 区域性。

然后,我将日期与 DateTime.Now 进行比较,看看它是否是过去的。

问题是, DateTime.Parse 将我的字符串转换为 dd.MM.yyyy 格式,但 DateTime.Now 具有 MM.dd.yyyy 格式,所以比较总是失败。

在相同的线程区域性中,为什么 DateTime.NowDateTime.Parse 的输出不同?

谢谢!

(更新)这是我正在使用的代码:

InputText包含来自DD.MM.YYYY格式的表单的输入

DateTime date = DateTime.Parse(InputText, CultureInfo.CurrentCulture);
// Check it's not in the past
this.IsValid = (date.CompareTo(DateTime.Now) > 0);

[DateTime.Now]在此上下文中是使用lv-LV CultureInfo的MM.DD.YYYY格式 DateTime.Parse 之后的 [date] 格式为 DD.MM.YYYY

I am sending in a string in dd/MM/yyyy format, which is then being parsed into lv-LV culture as set per the web.config globalization setting.

I am then comparing the date to DateTime.Now to see if it is in the past.

The problem is, DateTime.Parse converts my string to dd.MM.yyyy format, but DateTime.Now has MM.dd.yyyy format, so the comparison always fails.

Why would DateTime.Now be different to the output from DateTime.Parse, on the same thread culture?

Thanks!

(Update) This is the code I am using:

InputText contains input from a form in DD.MM.YYYY format

DateTime date = DateTime.Parse(InputText, CultureInfo.CurrentCulture);
// Check it's not in the past
this.IsValid = (date.CompareTo(DateTime.Now) > 0);

[DateTime.Now] in this context is in MM.DD.YYYY format using lv-LV cultureInfo
[date] is in DD.MM.YYYY format after the DateTime.Parse

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

谁与争疯 2024-10-12 09:20:42

DateTime 没有格式——它只是一个时间点。

如果您正在查看它,则意味着您正在输出它。使用正确的区域性来输出日期。

DateTime.ToString 具有重载,需要格式提供程序,例如 CultureInfo

string formatted = DateTime.ToString(new CultureInfo("lv-LV"));

如果未指定(在代码或配置中),则将使用默认系统区域性(或在某些情况下使用 CultureInfo.InvariantCulture)。

A DateTime does not have formatting - it is simply a point in time.

If you are viewing it, that means you are outputting it. Use the correct culture to output the date.

DateTime.ToString has overloads that take a format provider such as a CultureInfo:

string formatted = DateTime.ToString(new CultureInfo("lv-LV"));

If not specified (in code or configuration), the default system culture will be used (or CultureInfo.InvariantCulture, in some cases).

晨曦÷微暖 2024-10-12 09:20:42

如果您只想比较两个日期,则无需先转换为字符串。

DateTime myDate = DateTime.Parse(myDateAsString);//with the correct locale to ensure it's correctly parsed
if (myDate < DateTime.Now)
{
  //it's in the past
}

If you just want to compare the 2 dates, you don't need to convert to string first.

DateTime myDate = DateTime.Parse(myDateAsString);//with the correct locale to ensure it's correctly parsed
if (myDate < DateTime.Now)
{
  //it's in the past
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文