简体   繁体   中英

How to get time 2 hours earlier using Calendar API?

I need to get my start date and time as todays date and time should be 00:00 but end time should be current hour - 2. With me below code, I am not able to understand how to get end time as current hour - 2.

DateFormat df = new SimpleDateFormat("yyyy/MM/dd HH:mm");
Calendar startDate = new GregorianCalendar();
startDate.set(Calendar.MINUTE, 0);
Calendar endDate = (Calendar) startDate.clone();
startDate.set(Calendar.HOUR_OF_DAY, 0);

String startTime = df.format(startDate.getTime());
String endTime = df.format(endDate.getTime());

System.out.println(startTime);
System.out.println(endTime);    

If I run the above code just now, this is what gets printed out :

2015/08/17 00:00
2015/08/17 12:00

But I want to have end time as 10:00 which is 2 hours earlier than noon time so it should print this:

2015/08/17 00:00
2015/08/17 10:00

How can I do this?

UPDATE:-

This is what I have tried:

    Calendar startDate = new GregorianCalendar();
    startDate.set(Calendar.MINUTE, 0);
    Calendar endDate = new GregorianCalendar();
    endDate.add(Calendar.HOUR, -2);

    String startTime = df.format(startDate.getTime());
    String endTime = df.format(endDate.getTime());

    System.out.println(startTime);
    System.out.println(endTime);

And this is what it is printing out:

2015/08/17 12:00
2015/08/17 10:53

You can use the Calendar 's add(int field, int amount) method to add a negative number of hours. Like so:

Calendar date = new GregorianCalendar();
date.add(Calendar.HOUR, -2);

Link to the documentation

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM