How do I increment a java.sql.Timestamp by 14 days?

后端 未结 4 2057
借酒劲吻你
借酒劲吻你 2020-12-09 08:47

I have an app that takes a Timestamp as a boundary for the start date and end date of a sql selection, I want to populate a hashmap with weeks this year since the first mon

相关标签:
4条回答
  • 2020-12-09 08:57

    It worth noting that 14 days is not always 14 * 24 * 3600 seconds. When you have daylight savings, this can be an hour shorter or longer. Historically it can be much more complex than that.

    Instead I would suggest using JodaTime or the Calendar to perform the time zone dependant calculation.

    0 讨论(0)
  • 2020-12-09 09:05
    private Long dayToMiliseconds(int days){
        Long result = Long.valueOf(days * 24 * 60 * 60 * 1000);
        return result;
    }
    
    public Timestamp addDays(int days, Timestamp t1) throws Exception{
        if(days < 0){
            throw new Exception("Day in wrong format.");
        }
        Long miliseconds = dayToMiliseconds(days);
        return new Timestamp(t1.getTime() + miliseconds);
    }
    
    0 讨论(0)
  • 2020-12-09 09:15
    java.sql.Timestamp ts = ...
    Calendar cal = Calendar.getInstance();
    cal.setTime(ts);
    cal.add(Calendar.DAY_OF_WEEK, 14);
    ts.setTime(cal.getTime().getTime()); // or
    ts = new Timestamp(cal.getTime().getTime());
    

    This will correctly cater for daylight-time transitions in your default Timezone. You can tell the Calendar class to use a different Timezone if need be.

    0 讨论(0)
  • 2020-12-09 09:15

    Java 8

    Timestamp old;
    ZonedDateTime zonedDateTime = old.toInstant().atZone(ZoneId.of("UTC"));
    Timestamp new = Timestamp.from(zonedDateTime.plus(14, ChronoUnit.DAYS).toInstant());
    
    0 讨论(0)
提交回复
热议问题