user2970840
user2970840

Reputation: 1361

How to cast this date pattern?

I have a date with this pattern:

var value = "2013/11/07 23:08:53 +0000"

When I do:

var date = (DateTime)value;

I get an InvalidCastException. How can I cast that date?

Upvotes: 0

Views: 51

Answers (1)

Alex Wiese
Alex Wiese

Reputation: 8370

You can't cast a string to a DateTime. Instead use DateTime.Parse(value) to parse the value.

You can also use DateTime.TryParse(string) to avoid throwing an exception.

var value = "2013/11/07 23:08:53 +0000";

DateTime dateTime;

if(DateTime.TryParse(value, out dateTime))
{
    // The string is a valid DateTime

    // This will output '11:08 PM'
    Console.WriteLine(dateTime.ToShortTimeString());
}
else
{
    // The string is not a valid DateTime
}

Upvotes: 1

Related Questions