【问题标题】:Convert Linux datetime to Windows local datetime format将 Linux 日期时间转换为 Windows 本地日期时间格式
【发布时间】:2023-03-18 05:35:01
【问题描述】:

我有一个 ssh Linux 机器并在其上运行 date 命令的功能,并以字符串格式返回 Linux 机器日期。当我尝试将该字符串转换为日期时间格式时,会出现错误:

字符串未被识别为有效的日期时间

以下是我的代码:

DateTime appservertime = Convert.ToDateTime(GetLinuxServerTime(kvp.Value));

public string GetLinuxServerTime(string ip)
{
    using (var client = new SshClient(ip.Trim(), UserName, Password))
    {
         string a = "";
         client.Connect();
         SshCommand x = client.RunCommand("date");
         a = x.Result.ToString();
         //a.value= Tue Jun 19 11:54:34 EDT 2018

         client.Disconnect();
         return a;
    }
}

我需要将Linux日期时间转换成本地机器日期时间格式(不是硬编码格式)。

【问题讨论】:

  • 你可以使用DateTime.ParseExact()
  • 实际上,我正在开发将部署在生产服务器上的windows服务,不同的服务器可能有不同的时间格式。所以,不能在 DateTime.ParseExact 中指定格式。 @itsme86
  • GetLinuxServerTime(kvp.Value) 方法的返回值到底是多少?你应该调试你的代码并告诉我们。
  • 为什么不简单点,在linux机器上设置ntpd呢?

标签: c# linux windows datetime ssh


【解决方案1】:

指定date 命令的格式:

date +%Y%m%d%H%M%S

并使用与该格式等效的 C# 将字符串解析回 DateTime:

DateTime appservertime = DateTime.ParseExact(
    GetLinuxServerTime(kvp.Value), "yyyyMMddHHmmss", CultureInfo.InvariantCulture);

像这样:

DateTime appservertime = DateTime.ParseExact(
    GetLinuxServerTime(kvp.Value), "yyyyMMddHHmmss", CultureInfo.InvariantCulture);

public string GetLinuxServerTime(string ip)
{
    using (var client = new SshClient(ip.Trim(), UserName, Password))
    {
         client.Connect();
         SshCommand x = client.RunCommand("date +%Y%m%d%H%M%S");
         string a = x.Result.ToString();

         client.Disconnect();
         return a;
    }
}

【讨论】:

  • 它仍然给出无效的日期时间错误。以下是我的代码: DateTime appservertime = DateTime.ParseExact(GetLinuxServerTime(kvp.Value), "yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture); sshCommand x = client.RunCommand("date +\"%Y-%m-%d %H:%M:%S\"");
  • GetLinuxServerTime()返回的字符串值是多少?该值是否包含任何空格或换行符?
  • 是的。有空格。现在工作正常。谢谢彼得。
猜你喜欢
  • 2013-03-24
  • 2019-01-14
  • 2012-10-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-08-21
  • 1970-01-01
  • 2017-12-09
相关资源
最近更新 更多