C# Convert.ToDateTIme 函数是否将日期读取为“dd/mm/yyyy”或“mm/dd/yyyy”?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/771249/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-05 00:29:55  来源:igfitidea点击:

Does the C# Convert.ToDateTIme function read date as "dd/mm/yyyy" or "mm/dd/yyyy"?

c#.netsql-server-2005datetime

提问by Avinash

Does the C# Convert.ToDateTIme function read date as "dd/mm/yyyy" or "mm/dd/yyyy"?

C# Convert.ToDateTIme 函数是否将日期读取为“dd/mm/yyyy”或“mm/dd/yyyy”?

I have the same application on my local machine which I uploaded to my remote shared server. It was working perfectly on my local machine reading "dd/mm/yyyy", but on my remote machine, it seems to read dates as "mm/dd/yyyy". I have the same culture setting "en-GB" on both.

我在本地机器上有相同的应用程序,我上传到我的远程共享服务器。它在我的本地机器上完美地读取“dd/mm/yyyy”,但在我的远程机器上,它似乎将日期读取为“mm/dd/yyyy”。我在两者上都有相同的文化设置“en-GB”。

I find this date conversion very unpredictable. Can anyone recommend a culture-proof way of reading date strings from a SQL Server 2005 database?

我发现这个日期转换非常不可预测。任何人都可以推荐一种从 SQL Server 2005 数据库中读取日期字符串的文化证明方法吗?

回答by Chris

Why not simply use the datetime data type? Then, from your sql data reader, use: reader.GetDateTime(int column)

为什么不简单地使用 datetime 数据类型?然后,从您的 sql 数据阅读器中,使用: reader.GetDateTime(int column)

Another option: if you have to pass dates in strings, use the ISO format: yyyy-MM-dd

另一种选择:如果必须在字符串中传递日期,请使用 ISO 格式:yyyy-MM-dd

回答by Matt Hamilton

How are your dates actually stored in SQL Server? If they're stored as datetimethen you should be able to read them as DateTime values and not need to use Convert.ToDateTime(). Can you show us the query and/or the C# code?

您的日期实际上是如何存储在 SQL Server 中的?如果它们按原样存储,datetime那么您应该能够将它们作为 DateTime 值读取,而无需使用 Convert.ToDateTime()。你能告诉我们查询和/或 C# 代码吗?

Edit

编辑

You threw me off with the mention of SQL Server at the end of your question! Have you considered using a DateTimePicker instead of a TextBox? ASP.NET has date picker controls, right? Then it could do the parsing for you.

您在问题的结尾提到 SQL Server 时让我失望!您是否考虑过使用 DateTimePicker 而不是 TextBox?ASP.NET 有日期选择器控件,对吗?然后它可以为你做解析。

回答by Eoin Campbell

Well by the sounds of it... One of the settings on the server is off.

好吧,听起来……服务器上的一项设置已关闭。

I'd go through the "Region & Language" Options with a fine tooth comb and make sure that something isn't override but if that fails.

我会用细齿梳浏览“区域和语言”选项,并确保某些内容不会被覆盖,但如果失败。

You could try explicitly setting the Culture Info

您可以尝试明确设置文化信息

         string x = "21/01/2009";

        CultureInfo ci = new CultureInfo("en-GB");

        Convert.ToDateTime(x, ci);