MVC C# DateTime formatting fix needed - c#

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

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

DateTime : parsing unknown format

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!

Issue with datetime parsing

When I tried to parse the "2017-09-25T11:06:55+00:00" date string using TryParse method, I get the following output:
{9/25/2017 7:06:55 AM}
So, it's looks like 11 a.m. is getting converted into 7 a.m. Not sure why is this happening this? Is it because of +00:00??
What do I need to do so that parsed Datetime output is same: i.e. {9/25/2017 11:06:55 AM} ?
I tried using Current locale/culture and DateTime Styles. Assume Local but no luck.
(Note: I'm in the eastern time-zone)
Thanks.
You are using the UTC timezone (+00:00), but apparently, you or your PC is in -04:00 timezone.
If you can use DateTimeOffset, then I tend to prefer it. You get time zone info preserved, and you have access to both local and UTC datetime properties off this object.
var dt = DateTimeOffset.Parse("2017-09-25T11:06:55+00:00");
Console.WriteLine(dt.DateTime); // 9-25 at 11:06
Console.WriteLine(dt.UtcDateTime); // 9-25 at 11:06
Console.WriteLine(dt.LocalDateTime); // 9-25 at 07:06
If you know you're always going to be dealing with UTC, you can just parse by adjusting to universal like so:
var dt = DateTime.Parse("2017-09-25T11:06:55+00:00", CultureInfo.CurrentCulture, DateTimeStyles.AdjustToUniversal);
Console.WriteLine(dt); // 9-25 at 11:06
When you parse it initially it's the correct value, it's just now adjusted to be in your timezone. You can force it with ToUniversalTime :
DateTime.Parse("2017-09-25T11:06:55+00:00").ToUniversalTime().ToString("yyyy/MM/dd HH:mm:ss tt")
output
"2017/09/25 11:06:55 AM"
You want to parse correctly UTC DateTime and to have 9/25/2017 11:06:55 AM instead of 9/25/2017 7:06:55 AM. +00:00 is not correct UTC format, you need to change it to "2017-09-25T11:06:55z".
Here is working example

DateTime Parsing .Net 3.5

I have a string in my DB2 database which is physically located in US. I have a column value set to this string '2011-12-31 00:00:00' which indicates year 2011, month december and day 1st of the december.
I'm retrieving this as a string in my client program which is running in UK and the UI is set to local culture(the default). My client program also runs in US as well as in Hongkong with the culture set to the local culture there i.e US and HK respectively.
I'm using the following code for parsing the string into a datetime. I'm not very sure whether this is going to work, and I could't find any good link which points me to that direction. Could you please tell me whether this will work in various cultures, if not why?
string quarterStartDate = "2011-12-01 00:00:00";
DateTime quarterStart;
DateTime.TryParse(quarterStartDate, CultureInfo.InvariantCulture, DateTimeStyles.None, out quarterStart);
return quarterStart;
I have a test which works as per my requirement, but again 'am not too sure whether this will work when the UI is going to run in a different country.
string quarterStarter = "2011-12-01 00:00:00";
DateTime quarterStart;
DateTime.TryParse(quarterStarter,CultureInfo.InvariantCulture,DateTimeStyles.None,out quarterStart);
Assert.IsTrue(quarterStart.Year == 2011);
Assert.IsTrue(quarterStart.Month == 12);
Assert.IsTrue(quarterStart.Day == 1);
I would strongly suggest that as you know the format in advance, you use TryParseExact instead of TryParse:
bool success = DateTime.TryParseExact(quarterStarter, "yyyy-MM-dd HH:mm:ss",
CultureInfo.InvariantCulture,
DateTimeStyles.None,
out quarterStart);
Note that you should check the return value of TryParseExact to check that it's parsed correctly - if you're fine with an exception, just use ParseExact instead.
It's entirely possible that your existing code would work just fine - after all, you're already providing the invariant culture - but specifying the format makes it clearer what you really expect, and also means you'll detect if a value in an unexpected format is provided.
You can use ParseExact to pull the date, for example:
var s = "2011-12-01 00:00:00";
var dt = DateTime.ParseExact(s,"yyyy-MM-dd HH:mm:ss",CultureInfo.InvariantCulture);
You can set a specific format that does not change with culture.
DateTime dt;
DateTime.TryParseExact(dateTime,
"yyyy-MM-dd hh:mm tt",
CultureInfo.InvariantCulture,
DateTimeStyles.None,
out dt);

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

Categories