DateTime.ParseExact not working at all, why? - c#

I am attempting to parse the following String into a DateTime object in c#:
DateTime.ParseExact("20101108 230125", "yyyyMMdd hhmmss", null)
although the value looks correct the ParseExact method just keeps giving me the following:
String was not recognized as a valid DateTime.
Can anybody tell me why and how I can parse the above string without having to do it the manual way? Isn't ParseExact supposed to be for this kind of occasion?

You got the format for hours wrong, should be uppercase:
DateTime.ParseExact("20101108 230125","yyyyMMdd HHmmss", null)
Lowercase hh specifies that the time uses a 12-hour clock (with AM/PM). Uppercase HH is a 24 hour clock time.
For detailed info, check the documentation of custom DateTime format strings.

Try using:
var dt = DateTime.ParseExact("20101108 230125", "yyyyMMdd HHmmss", null)
The "hh" is for 12 hour time and "HH" for 24 hour.

Related

Date was not recognized as a valid DateTime

kinda got an issue that I cant solve right now.
I've got a discord bot running on my raspberry pi, which has a system for automated messages that are sent after a certain amount of time, or an exact date, has passed.
My code works on Windows when debugging there, but the console throws a warning on Linux when running the published project.
The date is taken from a table in my MySQL database and put into a DataTable. The code that grabs the date from the DataRow is:
DateTime datetime = DateTime.ParseExact(row["datetime"].ToString(), "dd.MM.yyyy HH:mm:ss", CultureInfo.InvariantCulture);
Why is it happening? No matter how I format the string (dots, dashes or slashes), the warning persists. The messages are not sent.
I even tried removing invisible whitespaces with regex, doesnt work either.
(The regex in question, though I scrapped it since it yielded no fruit anyways)
Regex.Replace($"{row["datetime"].ToString()}", #"[^\d\s\.:]", string.Empty);
If RDBMS type is DateTime then why should we convert to string and then parse it back to DateTime? Let's do it direct:
DateTime datetime = Convert.ToDateTime(row["datetime"]);
and let .net convert boxed DateTime (row["datetime"] is of type object?) to DateTime
There are a couple issues--at the highest level, your ParseExact method is encountering a Date Time string that does not match the supplied format.
According to the code you posted, the expected format of is dd.MM.yyyy HH:mm:ss, and in your exception exception, shows a Date time string (8/2/2021 2:00:00 PM) that does not match:
contains / and your expected format has .
dd is a 2-digit day, but the input date time string only has single digit days
MM expects a two digit month and the input date time only has a single digit month
the string contains AM/PM, and your format neglects to account for that.
Finally it's not clear if your date format is Month Day Year, or Day Month year.
The second issue, is that ParseExact should be enclosed in a try/catch block, so that your code can handle the case when an unexpected formatted date time string is passed in, and not crash.
To solve this, wrap your call into a try/catch, and gracefully handle the FormatException
And then make sure the Format string matches the expected input string.
Here is the .NET reference for the various DateTime format tokens
The error message is letting you know the issue.
You have :
DateTime datetime = DateTime.ParseExact(row["datetime"].ToString(), "dd.MM.yyyy HH:mm:ss", CultureInfo.InvariantCulture);
Notable, you are saying that the date format is going to be "dd.MM.yyyy HH:mm:ss"
Then your error message is saying that you couldn't parse :
8/2/2021 2:00:00 PM
Which is essentially a format of "d/M/yyyy h:mm:ss tt" (Assuming that days come before months).
If you change your code to :
DateTime datetime = DateTime.ParseExact(row["datetime"].ToString(), "d/M/yyyy h:mm:ss tt", CultureInfo.InvariantCulture);
You should be good to go. DateTime.ParseExact does what it says on the tin, it parses the date format exactly how you say it should come. If you aren't sure you can use DateTime.Parse() (But you can occassionally run into issues where days/months are around the wrong way).
Tested using the following code :
var myDateString = "8/2/2021 2:00:00 PM";
DateTime datetime = DateTime.ParseExact(myDateString, "d/M/yyyy h:mm:ss tt", CultureInfo.InvariantCulture);
Console.WriteLine(datetime.ToString());

Issue regarding convert numeric value to 24 hrs format time

I was trying to convert a numeric value to 24 hours format time but the code is not working. Here is my code:
string xx =
Convert.ToDateTime(TimeSpan.FromHours(01).ToString())
.ToString("HH", System.Globalization.CultureInfo.InvariantCulture);
OR
string xx1 =
new DateTime(TimeSpan.FromHours(01).Ticks)
.ToString("HH", System.Globalization.CultureInfo.InvariantCulture);
OR
var t = DateTime.Now.TimeOfDay;
string xx2 =new DateTime(t.Ticks).ToString("hh:mm:ss tt");
OR
string ss = TimeSpan.FromHours(01).ToString("HH");
The above code is not working. I searched Google and everyone said use HH for getting hour in 24 hours format. Can anyone tell me if this is specific issue to my PC?
getting no error rather first line of code return 01 instead of 13.
Because you adding 1 hour from midnight. You should add 13 hour instead like;
string xx = Convert.ToDateTime(TimeSpan.FromHours(13).ToString())
.ToString("HH", System.Globalization.CultureInfo.InvariantCulture);
Since TimeSpan.FromHours(01).ToString() returns 01:00:00 as a string, Convert.ToDateTime parse this string as 13/01/2015 01:00:001.
And 24-hour clock representation of a 01 will be the same as itself no matter you use hh or HH specifier.
On your second example, you calculate your TimeSpan as a Ticks and DateTime(Int64) constructor calculates this time from 01/01/0001 and your DateTime evantually will be 01/01/0001 01:00:00 and still, it's 24-hour clock representation will be 01.
On your third example, you are calling DateTime(Int64) constructor with TimeOfDay property, that's why your DateTime will be 01.01.0001 15:10:36 (when I run your example right now) and it's hh:mm:ss tt representation will be 03:11:31 PM in InvariantCulture.
Your fourth line throws FormatException because there is no standard or custom HH format specifier of a TimeSpan.
1: Since you parse only hour without date, this method returns date part as a today

DateTime losing Milliseconds

I am parsing a date from a file as a string and converting it to DateTime so that I can compare it with a previous date. I am losing the milliseconds when I do this which are extremely important as I am missing lines from the file I am parsing.
Example of Date From File I am extracting: 2014/11/12 10:47:23.571
m_LatestProcessDate after I do ParseExact 12/11/2014 10:47:23
See below line of code I am using. Any ideas how I get around this?
DateTime m_LatestProcessDate = DateTime.ParseExact(m_CurrentDateString,
"yyyy/MM/dd HH:mm:ss.fff",
CultureInfo.InvariantCulture);
CodeCaster already explained your problem, I wanna add this as an answer if he let's me..
Don't worry! Your milliseconds didn't lost. They are still there. Sounds like you just didn't see them when you try to represent your m_LatestProcessDate and that's probably because your string representation of your DateTime doesn't have milliseconds part.
For example, if you use DateTime.ToString() method without any parameter, this method uses "G" standard format of your CurrentCulture.
This specifier formats your DateTime as ShortDatePattern + LongTimePattern. And no culture have Millisecond part on it's LongTimePattern.
For example; InvariantCulture has HH:mm:ss format which doesn't represent millisecond part.
You can see your milliseconds of your m_LatestProcessDate like;
Console.WriteLine(m_LatestProcessDate.ToString("fff")); // prints 571

DateTime formats C#

I have a string which needs to be converted and validated to a DateTime. The string is in the following format 'dd.mm.yy'
I am trying to convert it to DateTime using the following
string format = "dd.mm.yy";
date = DateTime.ParseExact(current.Substring(aiRule.AiLength), format,
CultureInfo.InvariantCulture);
but unfortunately this fails.
The question is how to convert a string in the format 'dd.mm.yy' to a DateTime ?
Thank you
mm means "minutes". I suspect you want "dd.MM.yy". See MSDN for more information about custom date and time format strings.
(In particular, read the part about the "yy" specifier and how it chooses which century to use. If you can possibly change the input to use a four digit year, that could save you some problems...)
the string format should be like this....
string Format = "dd.MM.yy"
mm is for showing minutes
MM is for showing months..
I hope it will helps you...
As earlier posts has already pointed out, mm means minutes and MM means months. I ran this test snippet and it works as expected:
string format = "dd.MM.yy";
string date = "27.10.11";
DateTime result;
result = DateTime.ParseExact(date, format, CultureInfo.InvariantCulture);
I'll tell something "heretical". If dd.MM.yy (with 2 or 4 yy) is the format of your local culture, then you could let the DateTime.Parse (not ParseExact!) do its work without setting it to CultureInfo.InvariantCulture, or perhaps setting it to your local culture like new CultureInfo("it-IT").

Trying to parse a DateTime in C#

I am trying to parse a DateTime in C# and have the following lines of code:
string dt =Convert.ToString( DateTime.FromFileTime(e8.sts[counter8].TimeStamp));
string format = "dd-MM-yyyy HH:mm:ss";
DateTime dateTime = DateTime.ParseExact(dt, format,CultureInfo.InvariantCulture);
When I debug dt is coming in as 05/18/2011 09:25:17 AM but I get an expection saying:
String was not recognized as a valid
DateTime.
Starting off, you have no need for the conversion.
DateTime.FromFileTime(e8.sts[counter8].TimeStamp) returns a DateTime already...
Even so, with the string you have provided, DateTime.Parse(str) will take care of you.
If you end up storing this value in a text file, and really are dead-set on using a custom format string to parse it (which you don't need to):
The format you have:
Day/Month/Year 24-hour:minute:second
But looking at your input date:
05/18/2011 09:25:17 AM
You want:
Month/Day/Year 12-hour:minutes:seconds AM/PM
The format for what you want is:
MM/dd/yyyy hh:mm:ss tt
Isn't this expected? Date 05/18/2011 09:25:17 AM doesn't match your format string dd-MM-yyyy HH:mm:ss. Your date is in format MM/dd/yyyy HH:mm:ss tt.
Try this:
DateTime dateTime = DateTime.Parse("05/18/2011 09:25:17 AM");
I don't see any reason for the conversion. Just use:
DateTime.FromFileTime(e8.sts[counter8].TimeStamp)
Your DateTime is coming in as MM-dd-yyyy but you are trying to parse it as dd-MM-yyyy
Change your format string to "MM-dd-yyyy HH:mm:ss tt"
You can tell this as dt, using your current format string, is trying to be parsed as the 5th day (dd) of the 18th month (MM) of 2011 (yyyy)...
EDIT:
Sorry, I completely missed the AM/PM designator, you need the tt part of the format string. This will handle the AM/PM part of the string
EDIT 2:
As per your most recent comment, you want to convert it into MM-dd-yyyy HH:mm:ss string, the all you need to do is:
var outputString = DateTime.FromFileTime(e8.sts[counter8].TimeStamp).ToString("MM-dd-yyyy HH:mm:ss");
You already have the TimeStamp in a val;id .NET DateTime object, so all you need to do is perform a .ToString() with the required time format.
DateTime parsed = DateTime.ParseExact(dt,"MM/dd/yyyy HH:mm:ss tt",CultureInfo.InvariantCulture);
s many of the others have explained here, the format needs to be changed. However even when I tried the formats they have suggested, I still received the same error that you did. Eventually I hit upon the right format to get successful results.
The format should be:
string format = "MM/dd/yyyy HH:mm:ss tt";
because you are specifying time pattern such as AM. If the month is given as single digit, eg: 5, then MM should be replaced with M. I used slash instead of hypen between the dates because that's how the original date had been given.

Categories