错误:在c#中转换为日期格式时,字符串未被识别为有效的DateTime [英] Error : String was not recognized as a valid DateTime while converting to date format in c#
问题描述
这是我要格式化的日期时间格式。我从twitter apis获取此日期格式
string date =Thu Jul 18 17:39:53 +0000 2013
我尝试了
Convert.ToDateTime(date).ToString(dd / MM / yyyy)
/ pre>
但它说
字符串未被识别为有效的DateTime。
解决方案这样做:
DateTime.ParseExact(dtStr, ddd MMM dd HH:mm:ss zzzz yyyy,CultureInfo.InvariantCulture)
ParseExact
和TryParseExact
允许使用自定义格式字符串。ddd
是缩写的日期名称,MMM
缩写的月份名称dd
24小时时钟格式的HH
小时,mm
分钟,ss
秒,zzzz
时区和yyyy
这些年。
我已经使用
CultureInfo.InvariantCulture
指定当前文化不被使用,但是 InvariantCulture 这是相似的到en-US
。
从你的代码行获取日期我试图做
date.ToString(dd / mm / yyyy),但得到字符串为12-12-2013,否
斜杠
/
是您当前文化的日期分隔符的替代字符ator这显然是-
。所以也可以使用CultureInfo.InvariantCulture
指定在不使用当前文化的情况下使用分隔符:string result = dateTime.ToString(dd / mm / yyyy,CultureInfo.InvariantCulture);
请参阅: /自定义格式说明
Here is the date time format i'm trying to format.I'm getting this date format from twitter apis
string date = "Thu Jul 18 17:39:53 +0000 2013"
i tried
Convert.ToDateTime(date).ToString("dd/MM/yyyy")
But it says
String was not recognized as a valid DateTime.
解决方案This works:
DateTime.ParseExact(dtStr, "ddd MMM dd HH:mm:ss zzzz yyyy", CultureInfo.InvariantCulture)
ParseExact
andTryParseExact
allows to use a custom format string.ddd
is the abbreviated day name,MMM
the abbreviated month name,dd
the day number,HH
hours in 24h clock format,mm
minutes,ss
seconds,zzzz
the time-zone andyyyy
the years.I have used
CultureInfo.InvariantCulture
to specify that the current culture is not used butInvariantCulture
which is similar to"en-US"
.works but after getting date from your line of code i tried to do date.ToString("dd/mm/yyyy") but get the string as 12-12-2013, no slashes
/
is a replacement character for your current culture's date-separator which is obviously-
. So also useCultureInfo.InvariantCulture
to specify that the separator should be used without using your current culture:string result = dateTime.ToString("dd/mm/yyyy", CultureInfo.InvariantCulture);
See: The "/" Custom Format Specifier
这篇关于错误:在c#中转换为日期格式时,字符串未被识别为有效的DateTime的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!