How to create a readable date and time from a string?
I'm using an api that returns the date as a string, like so:
2011-06-13T21:15:19Z
As you can imagine this is not the easiest format to understand. My goal is to get it to format like this:
9:15pm - 6/13/2011
Anyone know how to accomplish this? Do I need to use a regular expression or is there a way to convert this to a DateTime
?
NOTE: I have tried to use the DateTime.ParseExact
method but it didn't work. If this is the solution could you pl开发者_Python百科ease show me how to convert the example above. Thanks.
string date = "2011-06-13T21:15:19Z";
DateTime dt = DateTime.Parse(date);
I just tried it with TryParse and it worked. Using a try parse is better than parse because you can then handle for the cases the string didn't parse. If your certain the string being passed is static, then I guess it isn't necessary.
string Time = "2011-06-13T21:15:19Z";
DateTime t;
if (DateTime.TryParse(Time, out t))
{
//Works
}
DateTime.Parse
seems to work fine for that string:
var dt = DateTime.Parse("2011-06-13T21:15:19Z");
Console.WriteLine(dt.ToString("h:mmtt - M/d/yyyy"));
EDIT
If you want to get it the formatted string to look exactly how it is in your question, just throw a ToLower()
on it:
Console.WriteLine(dt.ToString("h:mmtt - M/d/yyyy").ToLower());
Also, all of the date and time string formatting options can be found here:
http://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx
DateTime.Parse is supposed to work with those ISO 8601 date strings.
Use DateTime.Parse.
void Main()
{
var date = DateTime.Parse("2011-06-13T21:15:19Z");
Console.WriteLine(date);
}
The format string you are looking for is "hh:mmtt \- M/d/yyyy"
.
精彩评论