C# 日期时间格式问题:字符串未被识别为有效的日期时间

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16014101/
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-09 23:43:00  来源:igfitidea点击:

Datetime format Issue: String was not recognized as a valid DateTime

c#asp.netdatetime

提问by Priya

I want to format the input string into MM/dd/yyyy hh:mm:ssformat in C#.
The input string is in format MM/dd/yyyy hh:mm:ss
For example :"04/30/2013 23:00"

我想在 C#中将输入字符串格式化为MM/dd/yyyy hh:mm:ss格式。
输入字符串的格式MM/dd/yyyy hh:mm:ss
例如:"04/30/2013 23:00"

I tried Convert.ToDateTime()function, but it considers 4 as date and 3 as month which is not what I want. Actually month is 04 and date is 03.

我尝试了Convert.ToDateTime()函数,但它认为 4 是日期,3 是月份,这不是我想要的。实际上月份是04,日期是03。

I tried DateTime.ParseExact()function also, But getting Exception.

DateTime.ParseExact()也试过函数,但得到异常。

I am getting error:

我收到错误:

String was not recognized as a valid DateTime.

字符串未被识别为有效的 DateTime。

采纳答案by Botz3000

Your date time string doesn't contains any seconds. You need to reflect that in your format (remove the :ss).
Also, you need to specify Hinstead of hif you are using 24 hour times:

您的日期时间字符串不包含任何秒。您需要在您的格式中反映出来(删除:ss)。
此外,如果您使用的是 24 小时制Hh则需要指定而不是:

DateTime.ParseExact("04/30/2013 23:00", "MM/dd/yyyy HH:mm", CultureInfo.InvariantCulture)

See here for more information:

浏览此处获取更多信息:

Custom Date and Time Format Strings

自定义日期和时间格式字符串

回答by Pranay Rana

change the culture and try out like this might work for you

改变文化并尝试这样可能对你有用

string[] formats= { "MM/dd/yyyy HH:mm" }
var dateTime = DateTime.ParseExact("04/30/2013 23:00", 
     formats, new CultureInfo("en-US"), DateTimeStyles.None);

Check for details : DateTime.ParseExact Method (String, String[], IFormatProvider, DateTimeStyles)

检查详细信息:DateTime.ParseExact Method (String, String[], IFormatProvider, DateTimeStyles)

回答by Arshad

try this:

尝试这个:

string strTime = "04/30/2013 23:00";
DateTime dtTime;
if(DateTime.TryParseExact(strTime, "MM/dd/yyyy HH:mm",  
   System.Globalization.CultureInfo.InvariantCulture, 
   System.Globalization.DateTimeStyles.None, out dtTime))
 {
    Console.WriteLine(dtTime);
 }

回答by Soner G?nül

You can use DateTime.ParseExact()method.

您可以使用DateTime.ParseExact()方法。

Converts the specified string representation of a date and time to its DateTime equivalent using the specified format and culture-specific format information. The format of the string representation must match the specified format exactly.

使用指定的格式和特定​​于区域性的格式信息将日期和时间的指定字符串表示形式转换为其等效的 DateTime。字符串表示的格式必须与指定的格式完全匹配。

DateTime date = DateTime.ParseExact("04/30/2013 23:00", 
                                    "MM/dd/yyyy HH:mm", 
                                    CultureInfo.InvariantCulture);

Here is a DEMO.

这是一个DEMO.

hhis for 12-hour clock from 01 to 12, HHis for 24-hour clock from 00 to 23.

hh是从 01 到 12 的 12 小时时钟,HH是从 00 到 23 的 24 小时时钟。

For more information, check Custom Date and Time Format Strings

有关更多信息,请检查 Custom Date and Time Format Strings

回答by Diorrini11

DateTime dt1 = DateTime.ParseExact([YourDate], "dd-MM-yyyy HH:mm:ss",  
                                           CultureInfo.InvariantCulture);

Note the use of HH (24-hour clock) rather than hh (12-hour clock), and the use of InvariantCulture because some cultures use separators other than slash.

请注意使用 HH(24 小时制)而不是 hh(12 小时制),以及使用 InvariantCulture,因为某些文化使用除斜线以外的分隔符。

For example, if the culture is de-DE, the format "dd/MM/yyyy" would expect period as a separator (31.01.2011).

例如,如果区域性是 de-DE,则格式“dd/MM/yyyy”将期望句点作为分隔符 (31.01.2011)。

回答by Anjan Kant

Below code worked for me:

下面的代码对我有用:

string _stDate = Convert.ToDateTime(DateTime.Today.AddMonths(-12)).ToString("MM/dd/yyyy");
String format ="MM/dd/yyyy";
IFormatProvider culture = new System.Globalization.CultureInfo("fr-FR", true);
DateTime _Startdate = DateTime.ParseExact(_stDate, format, culture);

回答by Manjay_TBAG

This can also be the problem if your string is 6/15/2019. DateTime Parse expects it to be 06/15/2019.

如果您的字符串是 6/15/2019,这也可能是问题。DateTime Parse 预计它是 06/15/2019。

So first split it by slash

所以先用斜线分割

var dateParts = "6/15/2019"
var month = dateParts[0].PadLeft(2, '0');
var day = dateParts[1].PadLeft(2, '0');
var year = dateParts[2] 


var properFormat = month + "/" +day +"/" + year;

Now you can use DateTime.Parse(properFormat, "MM/dd/yyyy"). It is very strange but this is only thing working for me.

现在您可以使用 DateTime.Parse(properFormat, "MM/dd/yyyy")。这很奇怪,但这只是对我有用的东西。

回答by yogesh lodha

You may use this type format (get formatted data from sql server)

您可以使用这种类型的格式(从 sql server 获取格式化数据)



FORMAT(convert(datetime,'16/04/2018 10:52:20',103),'dd/MM/yyyy HH:mm:ss', 'en-us')

格式(转换(日期时间,'16/04/2018 10:52:20',103),'dd/MM/yyyy HH:mm:ss','en-us')



CONVERT(VARCHAR,convert(datetime,'16/04/2018 10:52:20',103), 120)

CONVERT(VARCHAR,convert(datetime,'16/04/2018 10:52:20',103), 120)