سؤال

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?

هل كانت مفيدة؟

المحلول 2

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())

نصائح أخرى

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"));

When using ToString() without any format, it simply uses the default ToString() method. Use the format you specified again to get the wanted result.

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

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

regards

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top