DateTime
is backed by a number (ticks). It has no human-readable representation, at all! When you create a DateTime (by specifying each date component individually, or by parsing a date string), it converts the string date into a ticks.
So what are you seeing in the debugger? Well, that's the result of the DateTime object's default ToString() method. This depends on the culture of the thread which the code is running in. Unless you change it, it will be the same as the operating system culture by default.
Likewise, this culture is also used when parsing dates, so in the UK 5/1/2018 would be understood by DateTime.Parse(...)
as the 5th of January, 2018, whereas in the US it would be understood as the 1st of May, 2018.
How should you use this information?
Understand that the date format used in the debugger is based on your computer's culture, and it means nothing as to how the DateTime object will perform on computers in other cultures.
If you want to display the date to a user, you need to use the ToString()
methods (there are a few overloads) to produce a date formatted the way you want it to be. Of course, the parameterless ToString()
method will work fine if you just want it formatted for the end-user's culture.
If you need to send a specific format, again you should use one of the ToString()
overloads. For example, you can pass the format o
: DateTime.UtcNow.ToString("o")
, and it will print the date in an ISO8601 compliant format: 2018-04-28T15:31:00.000Z
You can find different format strings here (MS docs).
One last thing: "In db I must write it as yyyy/M/d hh:mm:ss tt
."
If you are using an SQL database (SQL Server, MySQL, etc.) and you are using a date-typed field in the database, you should build your SQL queries using parameters. You wouldn't need to format the date at all then, you could just pass the DateTime
object as a parameter.
See here for more information on the SQL injection vulnerability and how to use parameterized queries.