简体   繁体   English

奇怪的DateTime.Now()行为

[英]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. 我遇到一个奇怪的问题,即出于时间戳记日志文件的目的,在调用DateTime.Now时返回错误的时间。 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. 其中“ line”变量是传递给该特定方法的字符串。 The date is fine, and the time inside the logTime variable is 20 minutes slower than it should be. 日期很好,并且logTime变量中的时间比原先的时间慢20分钟。 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. 鉴于文件系统正确报告了文件上的时间,我为为什么DateTime.Now慢了20分钟而感到困惑-我确定这不是DST问题,因为我们一次只能移动1小时。

Has anyone else seen this issue or could at least point me in the right direction? 是否有其他人看到过这个问题,或者至少可以指出我正确的方向?

TIA 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 =月而不是分钟

'MM' means month “ MM”表示月份
'mm' means minutes “ mm”表示分钟

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 在这里您可以找到有关Standart String.Formats Of DateTime其他信息

怎么样

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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