DateTime.Parse,拉脱维亚文化设置
我发送的是 dd/MM/yyyy
格式的字符串,然后根据 web.config 全球化设置将其解析为 lv-LV
区域性。
然后,我将日期与 DateTime.Now
进行比较,看看它是否是过去的。
问题是, DateTime.Parse
将我的字符串转换为 dd.MM.yyyy
格式,但 DateTime.Now 具有 MM.dd.yyyy
格式,所以比较总是失败。
在相同的线程区域性中,为什么 DateTime.Now
与 DateTime.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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
DateTime
没有格式——它只是一个时间点。如果您正在查看它,则意味着您正在输出它。使用正确的区域性来输出日期。
DateTime.ToString
具有重载,需要格式提供程序,例如CultureInfo
:如果未指定(在代码或配置中),则将使用默认系统区域性(或在某些情况下使用
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 aCultureInfo
:If not specified (in code or configuration), the default system culture will be used (or
CultureInfo.InvariantCulture
, in some cases).如果您只想比较两个日期,则无需先转换为字符串。
If you just want to compare the 2 dates, you don't need to convert to string first.