I have date/time format, for example: "1-Mar-13 92230" According to this document and this link the format is as follows: "d-MMM-yy Hmmss", because:
Day is single digit, 1-30
Month is 3 letter abbreviation, Jan/Mar etc.
Year is 2 digits, eg 12/13
Hour is single digit for 24 hour clock, eg 9, 13 etc. (no 09)
Minute is standard (eg 01, 52)
Second is standard (eg 30, 02)
I'm trying to run the following code in my program, but I keep getting an error of "String was not recognized as a valid DateTime."
string input = "1-Mar-13 92330";
var date = DateTime.ParseExact(input, "d-MMM-yy Hmmss",
System.Globalization.CultureInfo.CurrentCulture);
Please help, I'm not too familiar with DateTime conversions, but I can't see where I've gone wrong here. Thanks!
UPDATE: Is this because time cannot be parsed without colons in between? (eg 1-Mar-13 9:22:30 gets parsed, but i have an external data source that would be impossible to rewrite from Hmmss to H:mm:ss)
The time() function is defined in time. h (ctime in C++) header file. This function returns the time since 00:00:00 UTC, January 1, 1970 (Unix timestamp) in seconds. If second is not a null pointer, the returned value is also stored in the object pointed to by second.
(Write Formatted Date and Time to String) In the C Programming Language, the strftime function stores characters into the array pointed to by s based on the string pointed to by format.
The time_t datatype is a data type in the ISO C library defined for storing system time values. Such values are returned from the standard time() library function. This type is a typedef defined in the standard <time.
The ctime() function in C++ converts the given time since epoch to a calendar local time and then to a character representation. A call to ctime(time) is a combination of asctime() and localtime() functions, as asctime(localtime(time)) . It is defined in <ctime> header file.
You could fix your date:
var parts = "1-Mar-13 92230".Split(' ');
if (parts[1].Length == 5)
{
parts[1] = "0" + parts[1];
}
var newDate = parts[0] + " " + parts[1];
var date = DateTime.ParseExact(newDate, "d-MMM-yy HHmmss", System.Globalization.CultureInfo.CurrentCulture);
From msdn:
If format is a custom format pattern that does not include date or time separators (such as "yyyyMMdd HHmm"), use the invariant culture for the provider parameter and the widest form of each custom format specifier. For example, if you want to specify hours in the format pattern, specify the wider form, "HH", instead of the narrower form, "H".
so you can try:
string input = "1-Mar-13 92330";
var date = DateTime.ParseExact(input, "d-MMM-yy Hmmss",
System.Globalization.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