c# - 异常 "String was not recognized as a valid DateTime"

标签 c# asp.net datetime

我收到字符串未被识别为有效的日期时间。以下函数中出现异常

public int GetTime()
{
    string time = "17-07-2015 01:11:25"
    time.Replace('-', '/');

    DateTime oldDate = Convert.ToDateTime(time);
    // Difference in days, hours, and minutes.
    DateTime newDate =Convert.ToDateTime(DateTime.Now.ToString("dd-MM-yyyy HH:mm:ss"));

    TimeSpan ts = oldDate - newDate;
    // Difference in days.
    int differenceInhours = ts.Hours;
    differenceInhours = differenceInhours * 60;
    int differenceInMinutes = ts.Minutes + 1;
    int BalanceTime = differenceInhours + differenceInMinutes;

    return BalanceTime;
}

17-07-2015 01:11:25 此日期存储在数据库中

最佳答案

你可以尝试这个,因为你知道日期时间的格式:

 DateTime oldDate = DateTime.ParseExact(time,"dd-MM-yyyy HH:mm:ss", CultureInfo.InvariantCulture);

关于c# - 异常 "String was not recognized as a valid DateTime",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31447787/

相关文章:

python - 将 isoformat 字符串转换为 python datetime 对象

python - timedelta 不适用于 isoformat time python

c# - 使用未知类型参数 (Action<any>) 调用 Action

asp.net - ASP.NET Webforms 中的 ViewState 替代方案

c# - 带有 16 位 Guid 的路由看起来很疯狂?

c# - 如何在 ApplicationUserManager 上使用 Identity 2.2 并且不使用 ILookupNormalizer

c# - OpenXml "Can not access a closed stream"仅在生产中

ruby-on-rails - 在 Ruby on Rails 中,DateTime、Timestamp、Time 和 Date 之间有什么区别?

c# - MessageBox 没有获得焦点

c# - 迁移到 .Net Core 3.1 时,.Net Core 2.2 中使用的 Services.AddMvc() 和 SuperJsonOutputFormatter 的替代方案是什么