sovon
sovon

Reputation: 907

add number to date(H:mm:ss:SSS) format

I want to add date formate(H:mm:ss:SSS).I did the following-

    Date time1;
    Date time2;
    String result1;
    SimpleDateFormat formatter;
    formatter = new SimpleDateFormat("H:mm:ss:SSS");
    time1 = new Date(0,0,0,0,0,5);
    time2=new Date(0,0,0,0,0,5);

the output of time1 is 0:00:05:000. Now i want to add those two time and make 0:00:10:000. but time1+time2 is not possible. is there any way to do this?

Upvotes: 0

Views: 275

Answers (2)

Unknown
Unknown

Reputation: 2137

You can use calendar for your requirement:

    Calendar calendar = Calendar.getInstance();
    calendar.setTime(new Date());
    calendar.set(Calendar.HOUR_OF_DAY,0);
    calendar.set(Calendar.MINUTE,0);
    calendar.set(Calendar.SECOND,5);
    calendar.set(Calendar.MILLISECOND,0);

    System.out.println(formatter.format(calendar.getTime()));

    Calendar another = Calendar.getInstance();
    another.setTime(calendar.getTime());
    another.set(Calendar.HOUR_OF_DAY,0);
    another.set(Calendar.MINUTE,0);
    another.set(Calendar.SECOND,calendar.get(Calendar.SECOND)+5);
    another.set(Calendar.MILLISECOND,0);

    System.out.println(formatter.format(another.getTime()));

OUTPUT:

0:00:05:000
0:00:10:000

Here is the Java Doc for Calendar

Upvotes: 3

Daan van der Kallen
Daan van der Kallen

Reputation: 543

new Date(time1.getTime() + time2.getTime()) should do the trick.

getTime() returns the milliseconds since January 1, 1970, 00:00:00 GMT.
new Date(0, 0, 0, 0, 0, 0) equals January 1, 1970, 00:00:00 GMT. so you basically only have the milliseconds of the 5 seconds in time1.getTime() and time2.getTime() so you can just sum these and convert it back to a Date object.

Upvotes: 1

Related Questions