0

Possible Duplicate:
How to convert Milliseconds to “X mins, x seconds” in Java?
Calculating the Difference Between Two Java Date Instances

I have a function like this:

 public String setDateAndTime(int h, int m, int s,int amPm) {
    TimeZone nst = TimeZone.getTimeZone("GMT+5:45");
    Calendar calendar1 = new GregorianCalendar(nst);
    Date currentTime1 = new Date();
    calendar1.setTime(currentTime1);


    calendar1.set(Calendar.HOUR, h);
    calendar1.set(Calendar.MINUTE, m);
    calendar1.set(Calendar.SECOND, s);
    calendar1.set(Calendar.YEAR, calendar1.get(Calendar.YEAR));
    calendar1.set(Calendar.MONTH, calendar1.get(Calendar.MONTH));
    calendar1.set(Calendar.DAY_OF_MONTH, calendar1.get(Calendar.DAY_OF_MONTH));
    calendar1.set(Calendar.AM_PM, amPm);


    DateFormat formatter = new SimpleDateFormat("hh:mm:ss a");
    String date = formatter.format(calendar1.getTime());

    return date;
}

Through this function i created two dates(String)

String s1=setDateAndTime(12,00,00,1);//12:00:00 PM
String s2=setDateAndTime(3,15,45,0);//3:15:45 AM

Now how to find to find difference between s1 and s2, i also need the hours, minutes and second lefts, so that i can do further processing.

Community
  • 1
  • 1
Binay
  • 149
  • 1
  • 3
  • 12
  • 2
    Did you search on SO?http://stackoverflow.com/questions/1555262/calculating-the-difference-between-two-java-date-instances – Azodious Jan 08 '13 at 11:54
  • 2
    I would start by making your function return a Date type, not a string – Brian Agnew Jan 08 '13 at 11:55
  • 1
    @BrianAgnew i need to display those times in a jsp page, so i used String instead of date. – Binay Jan 08 '13 at 11:57
  • Why don't you convert your time string into milliseconds, calculate your difference and convert it into a time string back? – Reporter Jan 08 '13 at 11:57
  • @Binay you should only convert to a String at the last moment before it is displayed. All your internal calculations should be using Date or ideally JodaTime's LocalDate – Peter Lawrey Jan 08 '13 at 11:58
  • @Azodious ya i searched in SO, i also went through the link that u posted, but, i didn't understand what unix timestamp is... – Binay Jan 08 '13 at 12:02
  • 2
    @PeterLawrey i will give it a try...and yes i'am from NEPAL...:) – Binay Jan 08 '13 at 12:08

1 Answers1

3

You can get time in milliseconds by calling getTime(). Then compare long values. milliis/1000 gives seconds, millis/60/1000 gives minutes, millis/3600/1000 gives hours, etc.

You can also use 3rd party libraries like JodaTime but if you need this one-time Joda is too much.

AlexR
  • 114,158
  • 16
  • 130
  • 208