What is the easiest way to convert the following date created using
dateTime.ToString("yyyyMMddHHmmss", CultureInfo.InvariantCulture)
into a proper DateTime
object?
20090530123001
I have tried Convert.ToDateTime(...)
but got a FormatException
.
Using strptime() , date and time in string format can be converted to datetime type. The first parameter is the string and the second is the date time format specifier. One advantage of converting to date format is one can select the month or date or time individually.
open System let convertToDateTime (value: string) = try let convertedDate = Convert. ToDateTime value printfn $"'{value}' converts to {convertedDate} {convertedDate.
The DateTime. ParseExact method converts the specified string representation of a datetime to a DateTime . The datetime string format must match the specified format exactly; otherwise an exception is thrown. Date & time is culture specific; the methods either use the current culture or accept a specific culture.
Try this:
DateTime.ParseExact(str, "yyyyMMddHHmmss", CultureInfo.InvariantCulture);
If the string may not be in the correct format (and you wish to avoid an exception) you can use the DateTime.TryParseExact
method like this:
DateTime dateTime; DateTime.TryParseExact(str, "yyyyMMddHHmmss", CultureInfo.InvariantCulture, DateTimeStyles.None, out dateTime);
http://msdn.microsoft.com/en-us/library/w2sa9yss.aspx
var date = DateTime.ParseExact(str, "yyyyMMddHHmmss", CultureInfo.InvariantCulture)
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