将.ToDateTime转换为特定格式

时间:2017-11-13 13:39:47

标签: c# datetime

我想要dd-MM-yyyy格式的日期。我已将其设置为Global.asax。但是当我尝试将日期字符串转换为DateTime时,它会出现以下错误。

  

mscorlib.dll中发生了'System.FormatException'类型的异常,但未在用户代码中处理。       附加信息:字符串未被识别为有效的DateTime。

我不想在字符串中传递日期(不想使用ToString('format'))。请帮忙。

以下是Global.asax中的代码。

protected void Application_BeginRequest(object sender, EventArgs e)
    {
        CultureInfo cInfo = (CultureInfo)System.Threading.Thread.CurrentThread.CurrentCulture.Clone();//new CultureInfo("en-IN");
        cInfo.DateTimeFormat.ShortDatePattern = "dd-MM-yyyy";
        cInfo.DateTimeFormat.LongDatePattern = "dd-MM-yyyy HH:mm:ss,fff";
        cInfo.DateTimeFormat.DateSeparator = "-";
        Thread.CurrentThread.CurrentCulture = cInfo;
        Thread.CurrentThread.CurrentUICulture = cInfo;
    }

Controller: -

public ActionResult Index(string dateParam)
    {
        DateTime? dataObj = dateParam != null ? DateTime.ParseExact(dateParam, "dd-MM-yyyy", System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None) : (DateTime?)null;
       // -- Do something --
        return View();
    }

0 个答案:

没有答案
相关问题