错误:在c#中转换为日期格式时,字符串未被识别为有效的DateTime [英] Error : String was not recognized as a valid DateTime while converting to date format in c#

查看:1277
本文介绍了错误:在c#中转换为日期格式时,字符串未被识别为有效的DateTime的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我要格式化的日期时间格式。我从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 and TryParseExact 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 and yyyy the years.

I have used CultureInfo.InvariantCulture to specify that the current culture is not used but InvariantCulture which is similar to "en-US".

Demo

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 use CultureInfo.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屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆