Steffano Soh
Steffano Soh

Reputation: 121

Conversion of date time in C#.net

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

Upvotes: 0

Views: 1820

Answers (4)

Daniel Schäffel
Daniel Schäffel

Reputation: 93

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"];

Upvotes: 0

Erdinç Özdemir
Erdinç Özdemir

Reputation: 1381

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

Upvotes: 0

Umesh
Umesh

Reputation: 2732

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

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

Upvotes: 0

to StackOverflow
to StackOverflow

Reputation: 124696

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.

Upvotes: 2

Related Questions