c# - 将 Linux 日期时间转换为 Windows 本地日期时间格式

标签 c# linux windows datetime ssh

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

String was not recognized as a valid DateTime

以下是我的代码:

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 日期时间转换为本地机器日期时间格式(不是硬编码格式)。

最佳答案

指定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;
    }
}

关于c# - 将 Linux 日期时间转换为 Windows 本地日期时间格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50931580/

相关文章:

c++ - 在控制台 C++ 中获取鼠标和键盘输入

windows - ffmpeg:在 Mac 上生成的 wmv 文件无法在 Windows 中播放

linux - 如果设备已经连接,udev ignore_device 将无法工作

c# - DataGridView 没有列

C# 二叉搜索树 - 堆栈溢出 - 调试

C# 访问另一个项目的 app.config 时出现问题

PHP 使用系统调用为脚本设置超时,set_time_limit 不起作用

linux - 嵌入式 linux 中的 busybox 显示 "applet not found"

c++ - Visual Studio 2010 win32 编译的应用程序不能在 windows xp 上运行

c# - 绘制和更新 PictureBox