【问题标题】:MVC DateTime Not ConvertingMVC 日期时间未转换
【发布时间】:2018-01-13 10:20:20
【问题描述】:

我希望他们所有的 DateTime 格式都是这样的:MM/dd/yyyy HH:mm:ss

我试试这个:

DateTime time= aModel.time; //{13.01.2018 08:30:00}
string formatcurrenttime = String.Format("{0:MM/dd/yy HH:mm:ss}", time);
DateTime formattedTime = Convert.ToDateTime(formatcurrenttime);

但是给出错误,不起作用。例外:

字符串未被识别为有效的日期时间。

我试试这个:

CultureInfo cultureinfo = new System.Globalization.CultureInfo("en-US");
DateTime time= aModel.time; //{13.01.2018 08:30:00}
string formatcurrenttime = String.Format("{0:MM/dd/yy HH:mm:ss}", time);
DateTime formattedTime = DateTime.Parse(formatcurrenttime2, cultureinfo);

给定错误。

我试试这个:

DateTime formattedTime = DateTime.Parse(formatcurrenttime, System.Globalization.CultureInfo.InvariantCulture);

但又报错了。

出了什么问题?

注意:第一个代码是昨天工作的。今天不上班。通过托管公司更改我的 VDS 托管 IP 地址。我怀疑是 ASP.NET Culture 或 UI Culture 设置。

【问题讨论】:

  • 设置字符串格式后为什么要转回日期时间?
  • 哪个错误,也提供错误详情。
  • 您的代码在这里正常工作,没有错误。我可以来回转换。你得到什么错误?
  • 字符串未被识别为有效的日期时间。
  • 一个DateTime 对象有无格式

标签: c# datetime cultureinfo


【解决方案1】:

你不能传递带有dot的字符串格式, 正如您在 cmets 中所说,您想要像 01.13.2018 08:30:00 这样的格式,然后下面的代码可以工作。 因此,作为解决方法,您可以执行以下操作:

string stringTime = time.ToString("MM'.'dd'.'yyyy' 'HH':'mm':'ss");

string stringTime = time.ToString("MM.dd.yyyy HH:mm:ss");

那么如果你想传递不变的文化:

string stringTime = time.ToString("MM.dd.yyyy HH:mm:ss", CultureInfo.InvariantCulture);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-05-25
    • 2010-10-12
    • 1970-01-01
    • 2014-08-10
    • 2013-09-20
    相关资源
    最近更新 更多