【问题标题】:DateTime not appearing as per system format c# windows servicesDateTime 没有按照系统格式出现 c# windows services
【发布时间】:2015-02-25 12:33:17
【问题描述】:

当我们使用 System.DateTime.Now 时,它会根据系统中设置的内容显示 DateTime(如果我没记错的话)。 就像目前我的系统日期时间设置如下:

现在我用一个小的 sn-p 创建了一个简单的控制台应用程序:

Console.WriteLine(System.DateTime.Now);          
Console.WriteLine(System.Globalization.CultureInfo.CurrentCulture.DateTimeFormat.ShortDatePattern+" "+System.Globalization.CultureInfo.CurrentCulture.DateTimeFormat.ShortTimePattern);
System.IO.File.WriteAllText("E:\\perls.txt", System.DateTime.Now.ToString() + "\r\n" + System.Globalization.CultureInfo.CurrentCulture.DateTimeFormat.ShortDatePattern + " " + System.Globalization.CultureInfo.CurrentCulture.DateTimeFormat.ShortTimePattern);

控制台和文本的输出是:

现在我正在通过 Windows 服务做同样的事情,并在文本文件中记录一些信息,甚至创建与上面示例中创建的文件相同的文件: (我有一个简单的 Log 类,它记录了我没有进入其详细信息的信息) 所以代码如下:

Log.Info("System Date Time : " + System.DateTime.Now);
Log.Info("Date Time format : " + System.Globalization.CultureInfo.CurrentCulture.DateTimeFormat.ShortDatePattern + " " + System.Globalization.CultureInfo.CurrentCulture.DateTimeFormat.ShortTimePattern);
System.IO.File.WriteAllText("E:\\perls-service.txt", System.DateTime.Now.ToString() + "\r\n" + System.Globalization.CultureInfo.CurrentCulture.DateTimeFormat.ShortDatePattern + " " + System.Globalization.CultureInfo.CurrentCulture.DateTimeFormat.ShortTimePattern);

现在在我的日志文件(文本文件)中,我创建的文本文件提供以下输出:

两个样本都在同一个系统中执行,那么为什么会有这种差异? 我哪里错了? 或者这个问题只存在于我的系统中。

【问题讨论】:

  • 这个windows服务在哪里运行?另一个服务器?也许它有不同的文化背景? Log.Info 方法在尝试编写其字符串表示时如何处理 DateTime 值?
  • 如果您在第二个示例之前添加以下代码行会发生什么情况:System.Threading.Thread.CurrentThread.CurrentUICulture = System.Threading.Thread.CurrentThread.CurrentCulture;
  • @SonerGönül windows servcie 在我自己的系统中运行,输出也保存在我的系统中(文本文件)。 DateTime by Log 的写入方式与在文件中写入的方式相同,例如 DateTime time = DateTime.Now;我没有进入 Log 类的详细信息,因为它是一个我没有开发的 dll,但我知道它是正确的,因为如果我在控制台中使用日志,我会得到 -| 2015-02-25 20:54:22 |信息 | 2015-02-25 20:54:22 yyyy-MM-dd HH:mm:ss 即根据我系统中的设置.. 我认为日志没有任何问题

标签: c# datetime windows-services console-application


【解决方案1】:

您一定遇到了此处描述的问题 https://social.msdn.microsoft.com/Forums/vstudio/en-US/8fbca78b-5078-4a12-8abb-4051076febbb/c-windows-service-culture-info-problem

您的 Windows 服务很可能在具有注册表中定义的文化的服务帐户之一下运行。

看看你更新下面的注册表设置是否能解决问题。

[HKEY_USERS\.DEFAULT\Control Panel\International]
"Locale"="00000409"
"LocaleName"="en-US"

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-08
    • 2017-07-30
    • 2013-04-14
    • 1970-01-01
    • 1970-01-01
    • 2014-06-19
    相关资源
    最近更新 更多