I have a date represented as a string thus
20130116154407
I called DateTime.Parse on this but it failed. How can I convert this to a DateTime? Incidentally the timezone is CET.
EDIT
The solutions provided are very useful, so far but it seems they do not support 24 hour clocks, still looking for a solution that does.
EDIT 2
The correct format is
DateTime.ParseExact(str, "yyyyMMddHHmmss", CultureInfo.InvariantCulture)
Thanks,
Sachin
Only the ISO 8601 format ( YYYY-MM-DDTHH:mm:ss.sssZ ) is explicitly specified to be supported.
You can convert a DATETIME to a DATE using the CONVERT function. The syntax for this is CONVERT (datetime, format). This shows the date only and no time.
The Parse method tries to convert the string representation of a date and time value to its DateTime equivalent. It tries to parse the input string completely without throwing a FormatException exception.
ParseExact(String, String, IFormatProvider) Converts the specified string representation of a date and time to its DateTime equivalent using the specified format and culture-specific format information. The format of the string representation must match the specified format exactly.
You need to specify a format:
DateTime.ParseExact(str, "yyyyMMddHHmmss", CultureInfo.InvariantCulture)
Use this code
string DATE_FORMAT= "yyyyMMddhhmmss";
DateTime date;
if(DateTime.TryParseExact(str, DATE_FORMAT, DateTimeFormatInfo.InvariantInfo, DateTimeStyles.None, out date))
{
//success
//you can use date
}else
{
//fail
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With