Format date

Hi!

How can I ensure to have a universal date format (mm-dd-yyyy), independent of regional settings, in an application The code is this:

DateTime date = new DateTime();
date = DateTime.Now.Date;

Now, if regional setting is English-US, date value will be in "mm-dd-yyyy" format (9/22/2005). If the setting is not English, date format will be something else, like "dd-mm-yyyy" (22/9/2005). How can I "override" this
 


Answer this question

Format date

  • Codewarrior3

    Hi, Saurabh!

    You gave me an idea which actually works. I took the DateTime.Now.Date, and I converted it to string in the desired format. Then I used the date in string format in SQL sentence, and it WORKS ! T-SQL accepts the string as date! The idea never occured to me....

    Anyway, thanx a lot :)

    Regards,
    Aleksandra

  • Shane Griggs - MSFT

    I'm building a windows apllication. And the specific problem is this:

    I get the date from DateTime.Now.Date. Depending on the regianl setting, date format is either "mm-dd-yyyy" or "dd-mm-yyyy". Then I use that date to perform a search in a database. In the database, date format is "mm-dd-yyyy". Now, if the regional setting is set to "mm-dd-yyyy", then it's OK, I get the result I need. However, if the setting is set to "dd-mm-yyyy", then it doesn't work (naturally).

    Any thoughts
    My problem isn't displaying the date in the user interface - my problem is performing a search in the database with that date in the SQL sentence.

    Regards,
    Aleksandra 

  • dnelson

    What kind of application are you building YOu can manually set the Culture / UICulture of the CurrentThread to the spcific Culture you want. This way the dates will be formatted as per the specified culture.

    Also if you want to just show dates in partifulat formats then you can use the ToString method of the DateTime class which allows formatting options. Look out for the documentation on DateTimeFormatInfo class.

    So you can use expression like below to for the format to be MM-dd-yyyy irrespective of Regional settings.

    date.ToString("MM-dd-yyyy");

    Regards,
    Saurabh Nandu
    www.MasterCSharp.com




  • Format date