c#错误-系统.FormatException:字符串没有被识别为有效的日期时间

本文关键字:识别 有效 时间 日期 错误 系统 FormatException 字符串 | 更新日期: 2023-09-27 17:53:00

我一直在尝试在我的网站上输出时间。在我的本地主机上,它呈现/运行良好,但当我将文件上传到另一个环境/服务器时,它会产生错误"字符串未被识别为有效的日期时间"。我认为这是因为我使用的机器(我的笔记本电脑)和其他服务器的日期时间/时区的文化不同。我应该如何修改我的代码来匹配服务器?

DateTime starttime;
DateTime endtime;
starttime = Convert.ToDateTime(tempstarttime);
tempstarttime = starttime.ToString();
endtime = Convert.ToDateTime(tempendtime);
tempendtime = starttime.ToString();
if (schedlist[i, 2] == "PM" && schedlist[i + 1, 2] == "AM")
{
    //reformat schedlist[i+1, 2] to next day date + schedlist[i, 1]
    endtime = endtime.AddDays(1);
    exceedtonextday = 1;
}
if (exceedtonextday == 1)
{
    endtime = endtime.AddDays(1);
    starttime = starttime.AddDays(1);
}
if (comparetimesched(starttime, endtime))
{
    currentshow = "<span>" + schedlist[i, 1] + " " + schedlist[i, 2] + "</span><p>" + schedlist[i, 0] + "</p>";
    nextshow = "<span>" + schedlist[i + 1, 1] + " " + schedlist[i + 1, 2] + "</span><p>" + schedlist[i + 1, 0] + "</p>";
    showingimage = schedlist[i, 4];
    showingimagetwo = schedlist[i + 1, 4];
}

c#错误-系统.FormatException:字符串没有被识别为有效的日期时间

使用starttime = DateTime.Parse(tempendtime, CultureInfo.InvariantCulture)或您的本地文化代替Convert