Click here to Skip to main content
15,887,027 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
entered date is 2015-01-30

C#
System.Globalization.CultureInfo en = new System.Globalization.CultureInfo("en-US");
     System.Threading.Thread.CurrentThread.CurrentCulture = en;
     DateTime dt =Convert.ToDateTime(txbuyerOrder_date.Text, en.DateTimeFormat);


CSS
dt is always {30/01/2015 12:00:00 AM}

whether culture is en-GB or en-US or anything else
Posted
Updated 29-Jan-15 22:57pm
v2

1 solution

A DateTime doesn't have a format - it is stored as a number of milliseconds since an arbitrary point in time, so all it has is a number!

It only acquires a format when it is prepared for presentation to a user bymenas of the ToString method, either explicitly via a call:
C#
string myDate = dt.ToString();
Or implicitly:
C#
Console.WriteLine(dt);
Or
C#
string myDate = "The date is " + dt;

When the conversion to a string is done, the culture in effect on the PC doing the conversion controls how the resulting string is formatted.

[edit]
You can override the default formatting by specifying the exact output format you want - see here: Formatting a DateTime for display - format string description[^]
[/edit]
 
Share this answer
 
v2
Comments
varun150 30-Jan-15 5:19am    
string date32 = dt.ToString("yyyy-MM-dd");

it worked thanks.
OriginalGriff 30-Jan-15 5:23am    
You're welcome!
OriginalGriff 30-Jan-15 5:57am    
Silly question: why are you using ISO format dates?
You aren't going to use the string to pass a date to a database, are you?
varun150 31-Jan-15 4:35am    
yes yes i pass it to database. please tell me if there is something more to this.
OriginalGriff 31-Jan-15 4:50am    
There is more to this.
If you are converting the DateTime to a string to pass to a DB, then you are making two mistakes:
Firstly, you are converting it unnecessarily - you can pass a DateTime value from C# to a DB without any conversion and it will work.
Secondly, it implies that you are concatenating strings to form an SQL command, and that is very, very dangerous - it leaves you wide open to something called SQL Injection, where the user can take full control of your database, and accidentally or deliberately steal the information, damage, or destroy the database - just by typing on the screen.
You definitely shouldn't do that (particularly if this is a web-based app where the whole world has access to it) - use Parametrized queries instead.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900