0

I got Codes below, it generates my current time.

public static void main(String[] args) {
        long timeInMillis = System.currentTimeMillis();
        Calendar cal1 = Calendar.getInstance();
        cal1.setTimeInMillis(timeInMillis);
        SimpleDateFormat dateFormat = new SimpleDateFormat("hh:mm:ss a");
        String dateforrow = dateFormat.format(cal1.getTime());
        System.out.println(dateforrow );
}

Now How can I add hours to the current time? Like for example my current time 4:30:00 PM , and I want to add 8 hours to it, so maybe the output is 0:30:00 AM. I have no Idea.

Regie Baguio
  • 241
  • 5
  • 13

2 Answers2

2

You can try something like,

public static void main(String[] args) {
    long timeInMillis = System.currentTimeMillis();
    Calendar cal1 = Calendar.getInstance();
    cal1.setTimeInMillis(timeInMillis);
    cal1.add(Calendar.HOUR, 8);
    SimpleDateFormat dateFormat = new SimpleDateFormat("hh:mm:ss a");
    String dateforrow = dateFormat.format(cal1.getTime());
    System.out.println(dateforrow );
}
MSD
  • 1,409
  • 12
  • 25
문재호
  • 36
  • 2
1
        long timeInMillis = System.currentTimeMillis();
        Calendar cal1 = Calendar.getInstance();
        cal1.setTimeInMillis(timeInMillis);
        Date date = cal1.getTime();
        //add two hour
        date.setHours(date.getHours()+2);
       cal1.setTime(date);
        SimpleDateFormat dateFormat = new SimpleDateFormat("hh:mm:ss a");

        String dateforrow = dateFormat.format(cal1.getTime());
        System.out.println(dateforrow );

add two hour

Charif DZ
  • 14,415
  • 3
  • 21
  • 40