简体   繁体   中英

how to get today's date and add 7 days to it and the insert into oracle sql?

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?

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

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

       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());    

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);

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.

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 :)

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM