简体   繁体   中英

Odd DateTime.Now() behaviour

I'm having a weird issue where DateTime.Now is returning the incorrect time when I'm calling it for the purposes of timestamping a logfile. The code in question is as follows:

string logDate = DateTime.Now.ToShortDateString();
string logTime = DateTime.Now.ToString("HH:MM:ss");
string wLine = "[" + logDate + " " + logTime + "] " + line;
Console.WriteLine(wLine);

Where the 'line' variable is a string passed to that particular method. The date is fine, and the time inside the logTime variable is 20 minutes slower than it should be. The clock on the machine running this application is right, and if I delete the text file that it's writing to, it's recreated as soon as the app is run again, and the created / modified stamps on the file itself are correct.

Given that the filesystem reports the time on the file correctly, I'm stumped as to why DateTime.Now is 20 minutes slower - and I'm sure it's not a DST issue as we only ever move 1 hour at a time.

Has anyone else seen this issue or could at least point me in the right direction?

TIA

try change this :

string logTime = DateTime.Now.ToString("HH:MM:ss");

with

string logTime = DateTime.Now.ToString("hh:mm:ss");

MM = month not minute

'MM' means month
'mm' means minutes

You can make your code easier:
Just write

string wLine = "[" + DateTime.Now.ToString("G") + "] " + line;

instead of

string wLine = "[" + logDate + " " + logTime + "] " + line;

Here you can find additional information about Standart String.Formats Of DateTime

怎么样

Console.WriteLine("[{0:G}] {1}", DateTime.Now, line);

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