Question: ```
<%
   if(session == null) {
       System.out.println("Expire");
       response.sendRedirect("/login.jsp");
    }else{
       System.out.println("Not Expire");
    }
 %>

 <%
   HttpSession sess = request.getSession(false);
   String email = sess.getAttribute("email").toString();
   Connection conn = Database.getConnection();
   Statement st = conn.createStatement();
   String sql = "select * from login where email = '" + email + "' ";
   ResultSet rs = st.executeQuery(sql);
 %>

```

I tried to redirect the login.jsp page when session is expired.
But I am geeting error in "String email = sesss.getAttribute("email").toString();".

So anyone please help me to solve this error.

Basically I want to redirect to login.jsp page when the session is expired.

Answer: 
TimeSpan can be negative. So just substract the TimeSpan for 4PM with current [TimeOfDay](https://msdn.microsoft.com/en-us/library/system.datetime.timeofday), if you get negative value, add 24 hours.

```
var timeLeft = new TimeSpan(16, 0, 0) - DateTime.Now.TimeOfDay;
if (timeLeft.Ticks<0) 
{
    timeLeft = timeLeft.Add(new TimeSpan(24,0,0))
}

```
The answer is really simple, I should have seened this earlier. The solution to these kind of problems is basically modular arithmetic. The client requirment was the popup to show 24+ time to next 4 pm (Don't ask i don't know) so if:

program runs at 13:00 then the clock should display 24 +3 = 27

when 16:00 it should be 24+24 which is 48

when 22:00 it shoould be 24 + 18 which is 42

Now I noticed that:

13 + 27 = 40

16 + 24 = 40

22 + 18 = 40

40 Modulo 24 = 16

So basically if I subtract the current time from 40 then I will be left with the difference:

40 - 13 = 27

40 - 16 = 24

40 - 22 = 18

So what I did is this:

```
TimeSpan TimeToInstall;                
TimeSpan TimeGiven = new TimeSpan(23, 59, 59);        

DateTime Now = DateTime.Now;
long TimeTo4 = (new TimeSpan(40, 0, 0).Ticks - Now.TimeOfDay.Ticks) + TimeGiven.Ticks;
TimeToInstall = TimeSpan.FromTicks(TimeTo4);

```

EDIT
The above was a trap

Corrected:

```
DateTime Now = DateTime.Now;
if (Now.Hour < 16)
{
    long TimeTo4 = (new TimeSpan(40, 0, 0).Ticks - Now.TimeOfDay.Ticks);
    TimeToInstall = TimeSpan.FromTicks(TimeTo4);
}
else
{

    long TimeTo4 = (new TimeSpan(40, 0, 0).Ticks - Now.TimeOfDay.Ticks) + TimeGiven.Ticks;
    TimeToInstall = TimeSpan.FromTicks(TimeTo4);
}

```