.Net DateTime.ParseExact not working [duplicate] - c#

This question already has answers here:
How to convert datetime string in format MMMdyyyyhhmmtt to datetime object?
(2 answers)
Closed 6 years ago.
should the following parsing works,
DateTime.ParseExact("20150105 91353", "yyyyMMdd Hmmss", CultureInfo.InvariantCulture);;
I found out the above doesnt work, while the below, works,
DateTime.ParseExact("20150105 091353", "yyyyMMdd HHmmss", CultureInfo.InvariantCulture);;
I would like to know what is wrong with the first line of code.

This is one of the special cases where Custom DateTime format might find the input ambiguous.
When you do not have separator between hour and minutes, the single H format cannot distinguish the second number belongs to the hour or the minutes, thus your parse failed.
91353 //interpreted either as 9 13 53 or 91 35 3 - which one? ambiguous -> error
But this is ok:
string str = "20150105 9:13:53"; //no ambiguity with format yyyyMMdd H:mm:ss
string fmt = "yyyyMMdd H:mm:ss"; //can handle both "20150105 9:13:53" and "20150105 09:13:53"
DateTime dt = DateTime.ParseExact(str, fmt, CultureInfo.InvariantCulture);
To solve it, try to do little manipulation on your original string.
string dtstr = "20150105 91353";
string fmt = "yyyyMMdd Hmmss";
string[] parts = dtstr.Split(' ');
string str = parts[1].Length < 6 ? string.Join(" 0", parts) : dtstr;
DateTime dt = DateTime.ParseExact(str, fmt, CultureInfo.InvariantCulture);
Then it should be OK.

According to MSDN
If you do not use date or time separators in a custom format pattern, 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 pattern, specify the wider form, "HH", instead of the narrower form, "H".
This means this is correct DateTime.ParseExact("20150105 9:13:53", "yyyyMMdd H:mm:ss", CultureInfo.InvariantCulture); because it's using time separators

Related

Dateformat is right but getting String was not recognized as a valid DateTime

My dateformat is dd/MM/yyyy.
I have a date column in my file with values like 1/08/2019 to 31/08/2019.
But I'm getting the following error when processing that file:
System.FormatException: String was not recognized as a valid DateTime.
at System.DateTimeParse.ParseExact(String s, String format, DateTimeFormatInfo dtfi, DateTimeStyles style)
You've specified in your format string that the days and months must be double digits, but it appears that your input can be single digits.
In order to solve this, you need to specify a single digit in the format string by using a single d for the day portion (and a single M for the month, too).
It's also safe to use a single digit in the format string, since it will handle both single and double digits.
So your format string should look like: "d/M/yyyy"
For example, these all work:
var a = DateTime.ParseExact("1/8/2019", "d/M/yyyy", CultureInfo.CurrentCulture);
var b = DateTime.ParseExact("1/08/2019", "d/M/yyyy", CultureInfo.CurrentCulture);
var c = DateTime.ParseExact("01/8/2019", "d/M/yyyy", CultureInfo.CurrentCulture);
var d = DateTime.ParseExact("01/08/2019", "d/M/yyyy", CultureInfo.CurrentCulture);
difficult to say as you show the error but not the actual code, as you have dates in your file of differennt format, like d/MM/yyyy and dd/MM/yyyy try to use TryParse instead of ParseExact and if the TryParse fails with one format ( d/MM/yyyy ), then do another TryParse with the second format ( dd/MM/yyyy ) that way you should be able to cover both cases.
Again, without seeing the code it is difficult to give more detailed feedback.
also you could use an approach with TryParseExact and multiple format strings, like shown here:
var formatStrings = new string[] { "MM/dd/yyyy hh:mm:ss tt", "yyyy-MM-dd hh:mm:ss" };
if (DateTime.TryParseExact(dt, formatStrings, enUS, DateTimeStyles.None, out dateValue))
return dateValue;
see this SO answer: https://stackoverflow.com/a/17859959/559144

Convert string("2015-03-24T12:31:33.8700000") to c# datetime [duplicate]

This question already has answers here:
Convert string "Jun 1 2005 1:33PM" into datetime
(26 answers)
Closed 7 years ago.
I need to convert a string with date to valid c# date time object.
input string example = "2015-03-24T12:31:33.8700000"
output c# datetime
I tried doing this
DateTime.ParseExact(x.claimDetails.clmDOA, "yyyy-MM-dd HHmmss", CultureInfo.InvariantCulture)
Buit it gave exception
String was not recognized as a valid DateTime
Please Note: I googled thoroghly . Somehow i couldnt find any string
with "T" included as in datetime string.
Prior to downvoting if one can suggest me exactly where a question is answered with datetime string containg a T in it or of this format.yyyy-MM-dd'T'hh:mm:ss.fffffff
DateTime dt = DateTime.Parse(example);
DateTime dt = DateTime.ParseExact(example, "yyyy-MM-dd'T'hh:mm:ss.fffffff", CultureInfo.InvariantCulture);
Should work for you.
From DateTime.ParseExact documentation;
Converts the specified string representation of a date and time to its
DateTime equivalent. The format of the string representation must
match a specified format exactly or an exception is thrown.
In your case, they are not.
You need to use T as a string literal delimiter, specify : as a TimeSeparator and seconds fraction (with fffffff specifier) as well.
var dt = DateTime.ParseExact("2015-03-24T12:31:33.8700000",
"yyyy-MM-dd'T'HH:mm:ss.fffffff",
CultureInfo.InvariantCulture);
DateTime.ParseExact(example , "yyyy MM dd HH:mm:ss", CultureInfo.InvariantCulture);

Unable to parse DateTime with a custom format

After reading some other similar questions and trying their suggestions, I'm still unable to get my time to parse into a DateTime-
string time1 = File.ReadAllText(#"C:\Reminders\Reminder1Time.txt");
DateTime dt1 = DateTime.ParseExact(time1, "hh:mm:tt", CultureInfo.InvariantCulture);
dateTimePicker1.Value = dt1;
time1 is a string value of 9:00 AM Other questions have mentioned to use ParseExact to specify a custom format, but it's still not parsing.
The error I get thrown is on the second line
String was not recognized as a valid DateTime.
How would I get the dateTimePicker1 to display the value from the time1 string?
Looks like a stray colon and an extra h if you are expecting a 12 hour clock 1-12 without a leading zero and the AM PM marker with whitespace.
Try: h:mm tt
All of the formatting options are buried in the documentation, here.
var datefromFile = File.ReadAllText(FILELOCATION);
var format = "dd-MM-yyy hh:mm:ss,fff";
var formattedDateTime = DateTime.ParseExact(dateFromFile, format, CultureInfo.InvariantCulture);
Make your format Explicit, remember dd for date capital MM for month and yyyy for year. hh for hour mm for minutes and ss for seconds.
MSDN Formats:
https://msdn.microsoft.com/en-us/library/az4se3k1(v=vs.110).aspx

Convert custom formatted string to DateTime

I am trying to convert a string into a DateTime:
DateTime newDate = new DateTime();
DateTime.TryParse("20150620 800", out newDate);
The default value (1/1/0001 12:00:00 AM) is returned, how can this be correctly converted?
Use ParseExact to take a custom string and convert it,
According to 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".
This conversion is not possible, unless you change your input data.
You would expect this to work: (This really confused me for a bit while writing this)
DateTime newDate = DateTime.ParseExact("20150620 800", "yyyyMMdd Hmm", CultureInfo.InvariantCulture);
But since H must be in its widest form, it must be HH, as it thinks 80 is out of range for the hour measurement. You will need to add a space between 8 and 00, or add a 0 before 8.
These solutions will work:
DateTime newDate = DateTime.ParseExact("20150620 8 00", "yyyyMMdd H mm", CultureInfo.InvariantCulture);
DateTime newDate = DateTime.ParseExact("20150620 0800", "yyyyMMdd HHmm", CultureInfo.InvariantCulture);
If you cannot change this input data (eg, from a database), just perform a substring operation to insert a space between the minutes and hours so .NET can tell which is which:
var text = "20150620 800";
DateTime newDate = DateTime.ParseExact(text.Insert(text.Length - 2, " "), "yyyyMMdd H mm", CultureInfo.InvariantCulture);
DateTime.ParseExact(newDate,"yyyyMMdd Hmm", new DateFormatInfo());
Should work. Double check the .Net date format string reference to make sure it is what you want.

Datetime value to string by replacing c# [duplicate]

This question already has answers here:
extract the date part from DateTime in C# [duplicate]
(5 answers)
Closed 8 years ago.
I have a datetime value below,
23/07/2014 04:15:00
How can i get date as below string value
23/07/2014
How can i get hour as below string value
04:15 AM/PM (depends hour time)
Any help will be appreciated.
Thanks.
I'd parse the string to DateTime first to avoid string manipulation.
var str = "23/07/2014 04:15:00";
var dt = DateTime.ParseExact(str, "dd/MM/yyyy HH:mm:ss", CultureInfo.InvariantCulture);
var date = dt.ToString("dd/MM/yyyy", CultureInfo.InvariantCulture);//23/07/2014
var time = dt.ToString("hh:mm tt", CultureInfo.InvariantCulture);//04:15 AM
If you have the value as DateTime you can skip ParseExact part.
I'm not sure if you really use a DateTime instead of a string, but you should. If not, you can use DateTime.Parse/DateTime.TryParseExact to get a DateTime from a string.
DateTime has a method ToShortDateString
string dateOnly = dt.ToShortDateString();
// or to force / as separator even if current culture has different separator
dateOnly = dt.ToString("d", CultureInfo.InvariantCulture);
// hour+minute and AM/PM designator:
string hour = DateTime.Now.ToString("hh:mm tt", CultureInfo.InvariantCulture);
I strongly feel like taking a risk to answer your question but.. anyway.
How can i get date as below string value
DateTime dt = new DateTime(2014, 7, 23, 4, 15, 0);
Console.WriteLine(dt.ToString(#"dd\/MM\/yyyy")); // 23/07/2014
I escaped / character because it has a special meaning in custom date and time format strings. It means as; replace me with the current culture date separator. Take a look "/" Custom Format Specifier for more information.
How can i get hour as below string value
Console.WriteLine(dt.ToString("HH:mm tt", CultureInfo.InvariantCulture));
Output will be;
04:15 AM

Categories