user2691432
user2691432

Reputation: 93

Change datetime format

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

Answers (4)

Sameer
Sameer

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

Monah
Monah

Reputation: 6784

you can use the Format function for displaying the way you want

string.Format("{0:yyyy/M/d}",dateValue);

regards

Upvotes: 0

Steve
Steve

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

shirbr510
shirbr510

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

Related Questions