DateTime : parsing unknown format - c#

The following code will output 2018-10-03 16:40:50 (instead of 2018-03-10) :
DateTime dateTime = new DateTime();
DateTime.TryParse("10/03/2018 4:40:50 PM", out dateTime );
MessageBox.Show(dateTime.ToString());
The following code will parse the date correctly (2018-03-10)
dateTime = DateTime.ParseExact("10/03/2018 4:40:50 PM", "dd/MM/yyyy h:mm:ss tt", System.Globalization.CultureInfo.InvariantCulture);
MessageBox.Show(dateTime.ToString());
Is there any way to correctly parse this date without knowing the exact format?
The current culture of the server application is en-ca (English Canada) and I don't know the exact format of the string date to parse. at least is there a way to parse the date without the curious swap between the month and day? Sounds like an easy question but lost a lot of time reading and tried almost anything found here.
Thanks

End up using TryParseExact with an array list of known format. (ugly but it work)
There is no way to detect MM-DD-YYYY versus DD-MM-YYYY. Known limitation (this format is finally not supported by our application)
Thanks!

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());

Read non regular time format from excel in C#

I am trying to read non regular time format from excel in C#, the time value in excel is as "29-Aug-01 11.23.00.000000000 PM", and in excel the cells format is 'regular' not 'time'.
Now I need read the time in excel then assign the time into calendar time in asp.net/c#, how can I let the program understand the time format?
Big thx!
my code does not work
DateTime expTime = DateTime.ParseExact(strDate, "dd-MMM-yy hh.mm.ss.fffffffff tt", System.Globalization.CultureInfo.CurrentUICulture.DateTimeFormat);
I have similar solution, but more accur.
string s = "29-Aug-01 11.23.00.000000000 AM";
DateTimeOffset myDate = DateTimeOffset.ParseExact(
s,
"dd-MMM-yy hh.mm.ss.fffffff00 tt",
System.Globalization.CultureInfo.InvariantCulture);
EDIT:
You can't use more then 7 'f' chars.
The original format string fails because the DateTime type can't represent nanoseconds. The following format string will work:
var expTime = DateTime.ParseExact(strDate, "dd-MMM-yy hh.mm.ss.fffffff00 tt",
CultureInfo.InvariantCulture);
This works because the 00 characters are interpreted as literals and ignored during parsing.
Note that I'm passing CultureInfo.InvariantCulture instead of the system's UI Culture. This ensures that the English month abbreviations will be used even if the user's UI Culture is set to another language. Otherwise, DateTime.ParseExact will try to parse the date string using the user's language month abbreviations

Populating DateTime object with this string 03-06-2012 08:00 am

How to populate C# DateTime object from this "03-06-2012 08:00 am" string.
I'm trying some code of follwoing type:
DateTime lectureTime = DateTime.Parse("03-06-2012 08:00 am");
I am using jQuery based this http://trentrichardson.com/examples/timepicker/ plugin to generate date time.
Update --
So many answers below and lot of stuff to clear basics for this small issue
From the below snapshot u can see what I tried and what i received during debugging in visual studio
string lectureTime = "03-06-2012 08:00 am";
DateTime time = DateTime.ParseExact(lectureTime , "dd-MM-yyyy hh:mm tt", CultureInfo.InvariantCulture);
dd: days [00-31]
MM: months [00-12]
yyyy: years [0000-9999]
'-': these are separated with a dash
hh: hours [00-12]
mm: minutes[00-60]
tt: time [am, pm] (case insensitive)
If you have the correct culture, your code works without modification. But you may be using a different date formatting from the program that generated the string.
I'd recommend always specifying a CultureInfo when:
Parsing a DateTime generated by another system.
Outputting a DateTime that will be parsed by another system (not just shown to your user).
Try this:
CultureInfo cultureInfo = new CultureInfo("en-GB"); // Or something else?
DateTime lectureTime = DateTime.Parse("03-06-2012 08:00 am", cultureInfo);
See it working online: ideone
Difference between DateTime.Parse and DateTime.ParseExact
If you want .NET to make its best effort at parsing the string then use DateTime.Parse. It can handle a wide variety of common formats.
If you know in advance exactly how the dates should be formatted, and you want to reject anything that differs from this format (even if it could be parsed correctly and without ambiguity) then use DateTime.ParseExact.
You need to use DateTime.ParseExact. Something like
DateTime lectureTime = DateTime.ParseExact("03-06-2012 08:00 am", "dd-MM-yyyy hh:mm tt", CultureInfo.InvariantCulture);

MVC C# DateTime formatting fix needed

As you can see in the below screen shot. I have Date which is 7/12/2011 12:00:00 AM. Date is described wrong even if I format it. 7 should be the day and 12 is the month.
How I fix that to get proper formatting for yellow return string?
In the below screen shot the Date is 28/12/2011 11:00 where 28 is day and 12 is month. Trying to convert that string into DateTime to save into SQL Server DateTime field but gives conversion problem. Anyone tell me why is that and How to fix it?
Solution:
I solved problem like below. When I want saving date in SQL Server 2008 r2 the default was saved like 2011-08-12 11:00:00.000 which was causing problem. I changed that formatting Date when it was going to be saved in SQL like below and it worked
DateTime n = Convert.ToDateTime(start_date);
var h = String.Format("{0:dd/MM/yyyy}", n);
if (start_date != "")
{
changedEvent.start_date = Convert.ToDateTime(h);
}
Output now is 2011-12-08 11:00:00.000. Do you think any clean work around?
You should call DateTime.ParseExact(start_date, "dd/MM/yyyy", CultureInfo.InvariantCulture)
Try:
DateTime.ParseExact(str, "dd/MM/yyyy HH:mm:ss TT", null); //28/12/2011 11:00:00 AM
DateTime.ParseExact(str, "dd/MM/yyyy HH:mm", null); //28/12/2011 11:00
I think you are addressing the wrong problem. If you want DateTime to recognize your locale date format, then you should make sure the servers date locale is set for your local one. Then, DateTime will convert the date correctly without conversion.
If that's not possible (say you're using a shared server in a different locale) then the ParseExact method would be one solution, but it will only fix some of the problem. For instance, dates posted and model bound will attempt to parse in the servers locale format.
You may need to set your locale explicitly, using something like this:
Thread.CurrentThread.CurrentUICulture = new CultureInfo("es-MX");

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