9

I have two time values. one for the previous login time and one for the current login time. I have to increase previous time login by one hour. I have used the date format hh:mm:ss. This is my code snippet.

Date previous_time, current_time;

  if(previous_time.before(current_time)){
  Log.i("Time Comparision"," true");
 }

so instead of the above mentioned if condition, I have to add one hour to the previous_time and do the if condition. How to achieve this?

Andro Selva
  • 53,910
  • 52
  • 193
  • 240

3 Answers3

28
   Calendar calendar = Calendar.getInstance();
   calendar.setTime(previous_time);
   calendar.add(Calendar.HOUR, 1);
   previous_time = calendar.getTime();
   // do your comparison
planetjones
  • 12,469
  • 5
  • 50
  • 51
  • Sorry to say my friend. This code updates the hour, but it totally changes my date format. I want only time in the format "hh:mm:ss". – Andro Selva May 10 '11 at 13:12
  • 6
    @Andro_Selva - Formatting and the actual manipulation of the date are two independent tasks. Look at [DateFormat](http://download.oracle.com/javase/6/docs/api/java/text/DateFormat.html) and/or [SimpleDateFormat](http://download.oracle.com/javase/6/docs/api/java/text/SimpleDateFormat.html). – Rob Hruska May 10 '11 at 13:15
  • Then you can use SimpleDateFormat to get your wanted format. In your case "new SimpleDateFormat("hh:mm:ss").format(previous_time)", after the last line of planetjones. – dunni May 10 '11 at 13:16
  • Yep agree with @Rob Hruska (+1) - as the JavaDoc states "The class Date represents a specific instant in time, with millisecond precision" - formatting it is different to performing operations such as comparisons on it. – planetjones May 10 '11 at 13:27
  • @Andro_Selva, do you want to post some more code or explain your problem exactly - I can't infer what your issue is when you say "it didnt bring any difference" – planetjones May 10 '11 at 13:51
5
previous_time.setTime(previous_time.getTime() + 60 * 60 * 1000);

or

Date session_expiry = new Date(previous_time.getTime() + 60 * 60 * 1000);

http://download.oracle.com/javase/6/docs/api/java/util/Date.html#getTime%28%29

T-Bull
  • 2,136
  • 2
  • 15
  • 17
2

Please try this code.

    SimpleDateFormat sdf = new SimpleDateFormat("h:mm a");
    Date date = Utils.getBookingDate(mBooking.ToTime);
    Calendar calendarAdd = Calendar.getInstance();
    calendarAdd.setTime(date);
    calendarAdd.add(Calendar.HOUR, 1);
    toTime = sdf.format(calendarAdd.getTime());
    tv_Totime.setText(toTime);

when current time string formate within add 1 hours