简体   繁体   中英

Datetime to string: differents behavior depending on the converted datetime

I use this C# code to convert a datetime to a string:

MyDatetime.ToString("dd/MM/yyyy HH:mm")

it works, but not every time. What do I mean?

If the input datetime is, for example, 2016-10-19 17:27:41.727 , I get the string as expected, 19/10/2016 17:27 . If the day in datetime (and/or the month) has only one digit, I get something weird.

If the input is 2016-01-07 14:58:13.560 , I get 1/7/2016 and if it is 2016-10-26 17:14:16.000 I get 10/6/2016 .

Do you know why? How can I always set a leading zero for days and months with only one digit? And, further, why I don't see the time part in the date I wrote as examples?

UPDATE

这是我的意见 .

Some datetime fields from a SQL Server database (this is SQL Server Management Studio).

When you input a date as "XXXX-XX-XX" it assumes you're using the format "YYYY-MM-DD".

Just look at your input-output and you can see the pattern. A lot of people in programming (that I work with) use this format because it is auto-filtering without any punctuation (20170102 will always go after 20161231, etc).

Most probably your DateTime already has invalid value (day and month are mixed)

new DateTime(2016, 01,  07,14,58,13,56).ToString("dd/MM/yyyy HH:mm")

returns 07-01-2016 14:58 .

Take a look how do you read this DateTime value from the database. I believe the problem is there. (for example SqlDataReader.GetDateTime )

The DateTime method works in conjunction with the computer language. If your computer (or server) is in English (or vice versa) and you pass an American non-standard date format, you will have problems like this. If you are using a web application, configure the correct language in web.config

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM