-1

我使用 SimpleDateFormat 获取当前时间,我想返回 6 小时 30 分钟前的新时间。我尝试使用日历来执行此操作,但如果分钟数小于 30,它会返回负值。所以我的问题是,当需要从小时或天数借用时,是否可以这样做以返回正数。这是代码。我使用eclipse,程序正在编译和运行。

import java.text.DateFormat;
import java.text.NumberFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;


public class DifferenceInHours_04 
{

    public static void main(String[] args) 
    {
        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("dd MMM yyyy hh:mm:ss zzz" );
        System.out.println(sdf.format(date));

        Calendar cal = Calendar.getInstance();
        int hour = cal.get(Calendar.HOUR);
        int minute = cal.get(Calendar.MINUTE );
        int second = cal.get(Calendar.SECOND);
        System.out.println("Current time: "  + hour + ":" + minute +":" + second);

        int newHour = hour - 6;
        int newMinute = minute - 30;
        System.out.println("Modified time: " + newHour + ":" + newMinute + ":"+  second);

    }

}
4

1 回答 1

6

简单做

    Calendar cal = Calendar.getInstance();
    cal.add(Calendar.HOUR, -6);
    cal.add(Calendar.MINUTE,-30 );
    System.out.println("Time before 6 hour and 30 min from now is : "+ cal.getTime());
于 2012-06-18T08:11:10.210 回答