Reputation: 427
I have datetime data that looks like this: 2018-06-29T22:10:33Z
.
I need it in Short date format - 06/29/2018
i.e., without the time part.
I have tried the following in C#:
ConvertToDateTime(dateString);
DateTime.Parse(dateString);
Errors with both.
I'm resorting to dateString.substring(0,10)
to get the 1st 10 characters and convert that to date.
Is there a better method?
Upvotes: 1
Views: 1964
Reputation: 874
First and foremost, the date format appears to be not well formatted. The format you should be receiving should like "yyyy-MM-ddTHH:mm:ss.fffffffK" (i.e. "2018-06-29T22:10:05.1440844Z").
Assuming there was a typo in the sample date provided, here are a couple of samples to convert the date time string (in UTC format) to a DateTime:
var dateString = "2018-06-29T22:10:05.1440844Z";
var datetime = DateTime.ParseExact(dateString, "yyyy-MM-ddTHH:mm:ss.fffffffK", CultureInfo.InvariantCulture);
var date = datetime.Date;
or
var datetime = DateTime.ParseExact(dateString, "o", CultureInfo.InvariantCulture);
var date = datetime.Date;
You have to take into consideration that you are getting a UTC date and timezone conversions must be taken into consideration. Also, when just taking the date part, the time part is set to "12:00:00 AM".
Upvotes: 1
Reputation: 23797
You can use DateTime.TryParse method. ie:
string s = "2018-06-29T22:10:33Z";
DateTime t;
if (DateTime.TryParse(s, out t))
{
Console.WriteLine(t.ToShortDateString());
}
To get UTC date:
string s = "2018-06-29T22:10:33Z";
DateTime t;
if (DateTime.TryParse(s, out t))
{
Console.WriteLine(t.ToUniversalTime().ToShortDateString());
}
Upvotes: 2