且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

C#如何字符串转换成时间和日期格式?

更新时间:2022-10-26 19:57:52

经常需要给它一个关于提示您所期望的特定模式:



编辑:双空间是一种痛苦,因为 D 不处理是什么;

  DateTime的时间= DateTime.ParseExact(re.Replace(,),
DDD年MMM d HH:MM:SS YYYY,CultureInfo.CurrentCulture);


I have a short program which converts a string to both date and time format from a simple string.

However it seems that the String is not recorgnizable for the system to be converted into date time format due to the sequence of the string. The String that should be converted is an example like : "Thu Dec 9 05:12:42 2010"

The method of Convert.ToDateTime have been used but does not work.

May someone please advise on the codes? Thanks!

String re = "Thu Dec  9 05:12:42 2010";

DateTime time = Convert.ToDateTime(re);

Console.WriteLine(time.ToString("dddd, dd MMMM yyyy HH:mm:ss"));

It is often necessary to give it a hint about the specific pattern that you expect:

Edit: the double-space is a pain, as d doesn't handle that;

DateTime time = DateTime.ParseExact(re.Replace("  "," "),
     "ddd MMM d hh:mm:ss yyyy", CultureInfo.CurrentCulture);