문제

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