3

I am working on a program where I want to retrieve today's date in a servlet, then add some days to it say 7 days and then finally insert into oracle SQL database.

I am using prepared statement to do the call. Till now I have the current date using the following code.

DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy"); 
Date date = new Date();

How do I add 7 days to it and then insert it in the db?

  • 1
    Why are you using a `DateFormat` at all? That's only needed if you want to deal with text, and it doesn't look like you need any text here. Now, what exactly do you mean by "7 days"? Do you mean "7 x 24 hours of elapsed time"? Or do you mean "the same time, 7 days later"? Those are different things around DST transitions, assuming you're considering time zones. If you're happy using UTC, it's simpler... – Jon Skeet May 01 '15 at 06:01
  • Basically what i am trying to do is, get the current system date and add 7 days to it.. example todays date 01-05-2015 and make it 08-05-2015 and then insert into db. I was using date format to achieve this not sure if its the right approach. Any help? –  May 01 '15 at 06:04
  • 1
    No, it's not the right approach, because you shouldn't be using *text* for this at all. So you only need the date part, not a date/time - sorry not to have picked up on that before. Now, what time zone are you interested in? It's now May 1st for me, but April 30th for my colleague in California... – Jon Skeet May 01 '15 at 06:07
  • Oh, and which version of Java are you using? – Jon Skeet May 01 '15 at 06:08
  • http://stackoverflow.com/questions/12087419/adding-days-to-a-date-in-java for Date addition – MadProgrammer May 01 '15 at 06:16

7 Answers7

3

Based on your date format dd/MM/yyyy, I'm assuming that you're interested in only date but not date-time (timestamp like dd/MM/yyyy hh:mm:ss), you can do it easily in Java 8 with the new Date Time API in java.time package like this

LocalDate date = LocalDate.now();
date = date.plusDays(7);

In your PreparedStatement, you can use setObject like this

PreparedStatement ps = Connection.prepareStatement(sql);
ps.setObject(2,date); // 2 is the place holder for your date column

Note that these new classes are immutable like String, so any change on them will return a new object and you need to capture the return value after calling any method.

For more information, have a look at the API here

Arkantos
  • 6,530
  • 2
  • 16
  • 36
  • I think this should work for me. Let me check it once. –  May 01 '15 at 06:22
  • 1
    Note that this will give you the local date in which your JVM instance is running, you need to consider JonSkeet's advice about considering timezones if you think your application will be running in one location while your users can access it from any location – Arkantos May 01 '15 at 06:26
  • A significant thing to consider is the TZ difference between the _JVM and the database_; see my answer for details. – Mick Mnemonic May 01 '15 at 06:41
  • Yes i considered that but the project i am working on will be running locally on my system. No deployment elsewhere so localtime is good for me. –  May 01 '15 at 06:41
  • The j2ee version in eclipse i am using is not showing the localdate class. Any leads? –  May 01 '15 at 16:02
  • Do you have jdk8 version installed in your system ? If you already hv java8 then you need to map to that jdk in Windows - Preferences - Installed JREs – Arkantos May 01 '15 at 16:10
0

Get calendar instance, call setTime, call add, call getTime

https://docs.oracle.com/javase/7/docs/api/java/util/Calendar.html#setTime%28java.util.Date%29

https://docs.oracle.com/javase/7/docs/api/java/util/Calendar.html#add%28int,%20int%29

Alternately add the days to your prepared statement ... see This SO question as example

Community
  • 1
  • 1
saugata
  • 2,823
  • 1
  • 27
  • 39
0
       Calendar cal = Calendar.getInstance();
      cal.clear(Calendar.HOUR_OF_DAY);
      cal.clear(Calendar.AM_PM);
      cal.clear(Calendar.MINUTE);
      cal.clear(Calendar.SECOND);
      cal.clear(Calendar.MILLISECOND);
    int days = 7;
    // Add days
    calendar.add(Calendar.DAY_OF_MONTH, days);
    System.out.println(calendar.getTime());    
Ali
  • 1
  • 4
0

Use java.util.Calendar class Get the days (depends upon your requirement) add desired days to it Days can be Day in month or day in week or day in year I think for your requirement days in month is better...

java.util.Date date = new Date();
Calendar cal = Calendar.getInstance();
//date = cal.getTime();

int days = cal.get(Calendar.DAY_OF_MONTH);
cal.set(Calendar.DAY_OF_MONTH, days+7);
date = cal.getTime();
System.out.println(date);
Rookie007
  • 1,229
  • 2
  • 18
  • 50
  • 2
    Could you please [edit] your answer to give an explanation of why this code answers the question? Code-only answers are [discouraged](http://meta.stackexchange.com/questions/148272), because they don't teach the solution. – DavidPostill May 01 '15 at 08:21
0

You could let the DB do the arithmetic for you and do this:

PreparedStatement ps = null;
try {
    String sql = "INSERT INTO mytable (id, datecolumn) VALUES (?, trunc(?) + 7)";
    ps = myConnection.prepareStatement(sql);
    ps.setString(1, id);
    ps.setDate(2, new Date());
    // if your DB has a different timezone than your app server,
    // you should use this instead
    // ps.setDate(2, new Date(), Calendar.getInstance("<TZ of DB>"));
    ps.executeUpdate();
} finally {
    if (ps != null) {
        ps.close();
    }
}

This code inserts a date value to the target column having the time part set to zero (using Oracle's trunc function) and the date incremented by seven days.

It is important to note that if the timezone of your database is different from the JVM's, you should use the setDate overload that takes the TZ into account.

Mick Mnemonic
  • 7,808
  • 2
  • 26
  • 30
0

For adding let's say 7 days, Following code snippet would work:

      Calendar cal = Calendar.getInstance();
     //in below line of code, date is in which which you want to add 7 number of days
        cal.setTime(date);
        cal.add(Calendar.DATE, 7);
        java.util.Date utilDate = cal.getTime();
        java.sql.Date sqlDate = new java.sql.Date(utilDate.getTime());

Now you can use sqlDate value in your insert query.

Hope it helps :)

Reena Upadhyay
  • 1,977
  • 20
  • 35
0

java.time

The modern way is with java.time classes. The Question and other Answers use the troublesome old legacy date-time classes.

LocalDate

The LocalDate class represents a date-only value without time-of-day and without time zone.

A time zone is crucial in determining a date. For any given moment, the date varies around the globe by zone. For example, a few minutes after midnight in Paris France is a new day while still “yesterday” in Montréal Québec.

ZoneId z = ZoneId.of( "America/Montreal" );
LocalDate today = LocalDate.now( z );

Easy to do date math.

LocalDate weekLater = today.plusWeeks( 1 );

Database

If you have a database driver compliant with JDBC 4.2 or later, you should be able to pass the LocalDate object through JDBC with the PreparedStatement::setObject method.

myPreparedStatement.setObject( … , weekLater );

If not, you must convert to the old java.sql.Date class.

java.sql.Date sqlDate = java.sql.Date.valueOf( weekLater );
myPreparedStatement.setDate( … , sqlDate );

About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, .Calendar, & java.text.SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to java.time.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

Where to obtain the java.time classes?

  • Java SE 8 and SE 9 and later
    • Built-in.
    • Part of the standard Java API with a bundled implementation.
    • Java 9 adds some minor features and fixes.
  • Java SE 6 and SE 7
    • Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
  • Android

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

Community
  • 1
  • 1
Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154