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.
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.
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.
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");
}
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
);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With