Reputation: 93
I have below code :-
1) String str = DateTime.Now.ToString("M/d/yyyy")
Output :
str gives "2/3/2014"
2) DateTime dt = Convert.ToDateTime(DateTime.Now.ToString("M/d/yyyy"));
Output :
dt.ToString() gives "2014/02/03 12:00:00 "
But I'm not able to understand why it is not giving "2014/2/3 12:00:00 " ,i.e, without leading zeroes in day and month?
Upvotes: 0
Views: 6492
Reputation: 2171
The default format string for System.DateTime is "G" as in System.DateTime.ToString("G") where G is one of the presets. from source
Edit 1:
Globalization.CultureInfo customCulture = new Globalization.CultureInfo("en-US");
customCulture.DateTimeFormat.ShortDatePattern = "yyyy/M/d";
System.Threading.Thread.CurrentThread.CurrentCulture = customCulture;
System.Threading.Thread.CurrentThread.CurrentUICulture = customCulture;
DateTime dt = Convert.ToDateTime(DateTime.Now.ToString("M/d/yyyy"));
Console.WriteLine(dt.ToString())
Upvotes: 3
Reputation: 6784
you can use the Format function for displaying the way you want
string.Format("{0:yyyy/M/d}",dateValue);
regards
Upvotes: 0
Reputation: 216303
DateTime values have no format, it is the DateTime.ToString() method that outputs your datetime value in a particular format.
If you don't specify any parameter in the ToString() then the output is formatted using the general date and time format specifier ('G'). (Usually is the one set up in you control panel international settings)
Console.WriteLine(dt.ToString("M/d/yyyy"));
Upvotes: 5
Reputation: 858
When using ToString()
without any format, it simply uses the default ToString()
method.
Use the format you specified again to get the wanted result.
Upvotes: 0