减去日期值的时间

时间:2016-12-02 16:49:15

标签: java date

我实际上已经找到了最后三个日期,我想要做的是从每个日期减去5小时45分钟。怎么实现呢?

到目前为止,我所做的代码是:

public static List<Date> getPastThreeDays() {
    List<Date> pDates = new ArrayList<Date>();
    for (int i = 1; i <= 3; i++) {
        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.DATE, -i);
        Date date = cal.getTime();
        String pastDate = sdf.format(date);
        Date pstThreesDates;
        try {
            pstThreesDates = sdf.parse(pastDate);
            pDates.add(pstThreesDates);
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }
    return pDates;
}

public static void main(String[] args) throws ParseException {
    // for getting past three dates
    System.out.println("-----Formatted Past Three Days-----");
    List<Date> pastThreeDatesList = getPastThreeDays();
    for (Date date : pastThreeDatesList) {
        System.out.println("Orignal:" + date);
    }

3 个答案:

答案 0 :(得分:1)

如何避免依赖?

        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.DATE, -i);
        Calendar calLess5_45 = Calendar.getInstance();
        calLess5_45.setTimeInMillis(cal.getTimeInMillis() - (1000*60*45) - (1000*60*60*5));

或日期:

        Date initialDate = cal.getTime();
        Date dateLess5_45 = new Date(initialDate.getTime() - (1000*60*45) - (1000*60*60*5));

答案 1 :(得分:0)

将日期转换为毫秒,然后从中减去5小时45分钟,如下所示:

Komodo Dragon: How many are left in the wild?
Manatee: How many are left in the wild?
Kakapo: How many are left in the wild?
Florida Panther: How many are left in the wild?
White Rhino: How many are left in the wild?

答案 2 :(得分:0)

java.time

麻烦的旧日期时间类现在已经遗留下来,取而代之的是java.time类。

时区对于确定日期和添加减去天数至关重要。日期和日期长度因地区而异。

ZoneId z = ZoneId.of( "America/Montreal" );
ZonedDateTime zdtNow = ZonedDateTime.now( z );

减去一天。对夏令时等异常情况进行说明。

ZonedDateTime zdtYesterday = zdtNow.minusDays( 1 );

减去五小时四十五分钟的持续时间。

Duration d = Duration.ofHours( 5 ).plusMinutes( 45 );  // or Duration.parse( "PT5H45M" ) in standard ISO 8601 string format.
ZonedDateTime zdtEarlier = zdtYesterday.minus( d ) ;