C# How to convert String into Time and Date format?
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开发者_StackOverflow中文版 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"));
Take a look at DateTime.TryParseExact
DateTime time;
if (DateTime.TryParseExact(re,
"ddd MMM d hh:mm:ss yyyy", CultureInfo.CurrentCulture,
DateTimeStyles.None, out time)) {
Console.WriteLine(time.ToString("dddd, dd MMMM yyyy HH:mm:ss"));
} else {
Console.WriteLine("'{0}' is not in an acceptable format.", re);
}
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);
Take a look at DateTime.Parse
Try this
DateTime time = Convert.ToDateTime("2010, 9, 12, 05, 12, 42");
Console.WriteLine(time.ToString("dddd, dd MMMM yyyy HH:mm:ss"));
Not sure if the string input should have the double space but you could pull that out and use geoff's answer.
re = Regex.Replace(re, @"\s+", " ");
Other option is to adjust his match string accordingly.
DateTime time = DateTime.ParseExact(re, "ddd MMM d HH:mm:ss yyyy", CultureInfo.CurrentCulture);
精彩评论