字符串未被识别为有效的DateTime

时间:2012-04-20 13:35:45

标签: c# session datetime exception-handling

我想在会话中添加日期(date1),如下所示:

Session["DateLesson"] = date1.ToString("dd.MM.yyyy");

现在我要从会话中取这个值:

var asd = Session["DateLesson"];
/*asd = "20.04.2012"*/
var datelesson = DateTime.Parse((string) asd);

它给了我这个例外:

  

FormatException未被识别为有效的DateTime

4 个答案:

答案 0 :(得分:4)

在大多数区域设置中,句点不是有效/标准分隔符。您需要将DateTime.ParseExact()与格式字符串结合使用,以告诉函数如何读取它。更重要的是,如果将它读回日期时间是你的主要目标,为什么不把日期时间放在会话中呢?这似乎方式更有效,更容易,更易于维护。

答案 1 :(得分:1)

为什么要将日期保留为字符串?

您可以像这样存储它:

Session["DateLesson"] = date1;

然后像这样检索它:

var datelesson = (DateTime)Session["DateLesson"];

答案 2 :(得分:1)

string value = "20.04.2012";
DateTime datetime = DateTime.ParseExact(value, "dd.MM.yyyy", null);

这将返回4/20/2012 12:00:00:00 AM

答案 3 :(得分:0)

不要将值保留为字符串,而应保留为初始类型的对象:

public DateTime? DateLesson
{
    get
    {
        DateTime? dateTime = Session["DateLesson"] as DateTime?;
        if (dateTime.HasValue) // not null
        {
            // use dateTime.Value
        }
    }
    set
    {
        Session["DateLesson"] = value;
    }
}