Reputation: 3509
I want to know if there's a way to change the date format depending on the users local date format setting. The date I will store in the DB it's YYYY-MM-DD
but the users have different formats, like DD-MM-YYYY
or DD.MM.YYYY
. What is a clean, elegant way to ensure that my application always retrives the date in local date format, and SQL server always receives the date in YYYY-MM-DD
to be stored.
Upvotes: 1
Views: 227
Reputation: 51654
A DateTime
object doesn't have a format. You're probably talking about the string representation of the date.
You can return the date as a string using the user's respective culture settings by calling DateTime.ToShortDateString()
DateTime date = new DateTime(2012, 01, 01);
string dateStringInCurrentCultureFormat = date.ToShortDateString();
Upvotes: 0
Reputation: 27944
You should always save the date in a datetime object. To parse a date you can use DateTime.TryParseExcact when you know the date format and TryParse when you want to use your users prefrence. However it whould be nicer to use dedecated date controls to get a date from the user.
Upvotes: 0
Reputation: 273524
in the DB it's
YYYY-MM-DD
No. If you do it right the storage in the Db does not have a format. It is stored, for example, as a number.
What is a clean, elegant way to ensure that my application always retrives the date in local date format
Your application receives it as a binary value too. You have to think about format every time it becomes a string.
in local date format
For that you could rely on the machine configuration: datevalue.ToString()
.
But usually you want to take control: datevalue.ToString(specificCultureInfo)
Upvotes: 7