0

i'm having some problem converting a sessioned value of datetime to the correct format.

When i use DateTime lastlogged = Convert.ToDateTime(Session["LastLogin"]);i get the value {1/1/0001 12:00:00 AM} (got the value while debugging) but the actual value of Session["LastLogin"] is 2011-08-02 16:35:52.987 which is queried out from SQLServer 2008 data field datetime

3
  • 1
    Why do you need to convert the date to a string back and forth using a session variable ? Session variable can hold the date value in a boxed object. Commented Aug 2, 2012 at 9:21
  • What are the values of Session["LastLogin"]==null (you want false) and Session["LastLogin"].ToString() (you want that date)? Commented Aug 2, 2012 at 9:21
  • This seems like a string parsing issue. Try using DataTime.ParseExact(Session["LastLogin"].ToString(), "yyyy-mm-dd hh:mm:ss", CultureInfo.InvariantCulture); Commented Aug 2, 2012 at 9:39

4 Answers 4

2

Your result is DateTime.MinValue (midnight on 01/01/0001).

You'll get this result if the value in Session is null - this is the most likely explanation.

Sign up to request clarification or add additional context in comments.

Comments

0

If you storing the value correctly in Session, you can retreieve it through converting it to DateTime.

DateTime lastlogged = Convert.ToDateTime(Session["LastLogin"].ToString()); 

Comments

0
DateTime lastlogged = DateTime.Parse(Session["LastLogin"].ToString()); 

2 Comments

Doesn't compile. Parse need a string.
Yes, you're right. I forgot orgot .ToString() method. Changed the answer.
0

As the others already suggested you can use the DateTime.Parse method. But maybe it would be a better idea to use DateTime.TryParseExact. This way you can define the format of your DateTime

DateTime lastLogin; if (Session["LastLogin"] != null && DateTime.TryParseExact(Session["LastLogin"].ToString(), "yyyyMMdd", CultureInfo.InvariantCulture, DateTimeStyles.AssumeLocal, out lastLogin)) { // TODO: Code that uses the parsed date. } 

I'm not very familiar with the Session in ASP.net but isn't it also possible to store whole objects in it? This way it should also be possible to store the DateTime the way it is, resulting in a code that looks something like this:

DateTime result = (DateTime) Session["LastLogin"]; 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.