【问题标题】:C# Error - System.FormatException: String was not recognized as a valid DateTimeC# 错误 - System.FormatException:字符串未被识别为有效的 DateTime
【发布时间】:2015-06-02 12:23:47
【问题描述】:

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

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];

}

【问题讨论】:

  • tempstarttimetempendtime 的示例值是什么?
  • 你的CurrentCulture是什么?
  • 另外,为什么会这样:starttime = Convert.ToDateTime(tempstarttime); tempstarttime = starttime.ToString();?因此,您将字符串转换为DateTime,然后再转换回字符串。
  • 值从何而来,您真的需要将它们作为字符串获取吗? (此外,我认为您应该回顾一下 .NET 命名约定,顺便说一句......)
  • 使用特定的文化独立于操作系统文化。见这里:stackoverflow.com/questions/5590180/…

标签: c# string datetime sitecore formatexception


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-01-29
    • 1970-01-01
    • 1970-01-01
    • 2016-09-17
    • 2011-09-12
    • 2016-09-13
    相关资源
    最近更新 更多