Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DateTime.TryParse to other culture info

Tags:

date

c#

I currently have a time reporting project where you enter a date and report time for that date, ( all the dates are shown and sent back to the backend in swedeish format etc yy-mm-dd) But if I have another culture info on my computer like dd-mm-yyyy it will parse the date wrong and it won't work.

This is my code

DateTime reportDate;
if (!DateTime.TryParse(result, out reportDate))
{
    ModelState.AddModelError("Date", "Felaktikt datum");
}

This will take my yy-mm-dd and parse it to dd-mm-yyyy because that's what my computer is set to.

like image 247
Joakim Carlsson Avatar asked Aug 28 '15 09:08

Joakim Carlsson


People also ask

What does DateTime TryParse do?

TryParse(String, DateTime)Converts the specified string representation of a date and time to its DateTime equivalent and returns a value that indicates whether the conversion succeeded.

What is DateTime TryParse c#?

The DateTime TryParse method converts the string representation of a date and time to a DateTime object and returns true if the conversion was successful and false if otherwise.


2 Answers

You can specify the Swedish culture like this:

DateTime reportDate;

if (!DateTime.TryParse(result,
    System.Globalization.CultureInfo.GetCultureInfo("sv-SE"),
    System.Globalization.DateTimeStyles.None, out reportDate))
{
    ModelState.AddModelError("Date", "Felaktikt datum");
}
like image 84
Alex Warren Avatar answered Sep 28 '22 06:09

Alex Warren


DateTime.TryParse has an extra 2 parameters, the second is IFormatProvider which you can specify which culture you want it to be representing. In your case it's sv-SE which is Sweden.

DateTime.TryParse(
    result,
    new CultureInfo("sv-SE"),
    DateTimeStyles.None,
    out reportDate
);
like image 30
Orel Eraki Avatar answered Sep 28 '22 04:09

Orel Eraki