Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 monday of the year as the values and the week number as the keys. I'm finding it really hard to work with timestamps and I don't feel very good about adding 86,400,000 seconds to it to increment the day, as this doesn't account for the leap days, hours, seconds.

I plan on adding 13 days 23 hours, 59 minutes and 59 seconds to it so that I can lookup the start date in the map by the week as the key, then use the start date to get the end date.

So I'm looking to try to get something like this:

Week  startDate              endDate 1     2011-01-03 00:00:00    2011-01-16 23:59:59 2     2011-01-17 00:00:00    2011-01-30 23:59:59 

With the first two columns in the Map and the last one being calculated after looking it up. How do I safely increment a java.sql.Timestamp?

like image 767
davidahines Avatar asked Sep 16 '11 20:09

davidahines


People also ask

What is the format of Java SQL timestamp?

Formats a timestamp in JDBC timestamp escape format. yyyy-mm-dd hh:mm:ss.

How do you calculate timestamp in Java?

To get the current timestamp in Java, we can use the Timestamp class. Since this class does not have a default constructor, so we pass the time in milliseconds. We use the currentTimeMillis() method of System class to get the time.


1 Answers

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.

like image 96
Adrian Pronk Avatar answered Sep 29 '22 04:09

Adrian Pronk