我有一个 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/