I am storing Datetime in a session as mentioned below:-
Session["LoggedInTime"] = System.DateTime.Now;
Then i m retrieving this value on a page load like this:-
DateTime _loggedInTime = Convert.ToDateTime(Session["LoggedInTime"]);
I debug the above code code and find that up to here the _loggedInTIme is showing the correct date which i m storing in it. After that i m calculating the time span like this:-
TimeSpan elapsedtimespan = System.DateTime.Now.Subtract(_loggedInTime);
int elapsedtime = Convert.ToInt32(elapsedtimespan.TotalSeconds);
I found while debugging the code that ,while subtraction the _loggedInTime = {1/1/0001 12:00:00 AM} and due to which i m not able to get exact elapsedtime .
Please help me to solve this issue as i m not getting why the _loggedInTime become {1/1/0001 12:00:00 AM} at calculating TimeSpan.
The following works fine for me. Since you prefix _loggedInTime with an underscore I’m assuming you declared it as an instance variable of the page itself.
I’m guessing that you are calculating the elapsed time at another time and not in the Page_Load as in the above example.
Make sure that on each post back you correctly load the elapsed time from the session before calculating the elapsed time. On the next post back the _loggedInTime is reset to the default value of a DateTime, being {1/1/0001 12:00:00 AM}.
I think you have something to the following setup.
Here I demonstrate it by handling a postback when a button is clicked. In that case the Page_Load does not load the LoggedInTime and the elapsed time is calculated incorrectly. To solve this, just remove the IsPostBack if statement in the Page_Load. Make sure you set the instance variable _loggedInTime each time you load the page, thus also on a postback.
Remark: Also check if you are on a server farm. If you are using multiple servers to handle your requests but have configured the wrong session mode (e.g. in process) then server A will store the session variable in its memory, but the redirect can be handled by server B, which doesn’t know about server A’s in-memory session store.
More information can be found on MSDN:
Session-State Modes
In process session state is the default, in a server farm scenario you can use the StateServer or SqlServer alternatives to share session state between the servers. Or you can write your own custom session state provider.