Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I add 2 weeks to a Date in java? [duplicate]

Tags:

java

datetime

I am getting a Date from the object at the point of instantiation, and for the sake of outputting I need to add 2 weeks to that date. I am wondering how I would go about adding to it and also whether or not my syntax is correct currently.

Current Java:

private final DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
private Date dateOfOrder;

private void setDateOfOrder()
{
    //Get current date time with Date()
    dateOfOrder = new Date();      
}

public Date getDateOfOrder()
{
    return dateOfOrder;
}

Is this syntax correct? Also, I want to make a getter that returns an estimated shipping date, which is 14 days after the date of order, I'm not sure how to add and subtract from the current date.

like image 491
PugsOverDrugs Avatar asked Apr 26 '14 06:04

PugsOverDrugs


People also ask

How do you add weeks in Java?

Java LocalDate plusWeeks() and minusWeeks() Method. Java plusWeeks() and minusWeeks() both methods are included in Java 8 version with DataTime API. The minusWeeks() method is used to subtract weeks from a date created by LocalDate class similarly the plusWeeks() method is used to add weeks to a date.

How do I add 7 days to Java Util date?

Adding Days to the given Date using Calendar class Add the given date to the calendar by using setTime() method of calendar class. Use the add() method of the calendar class to add days to the date. The add method() takes two parameter, i.e., calendar field and amount of time that needs to be added.

How do you sum dates in Java?

long sum = d1. getTime() + d2. getTime(); Date sumDate = new Date(sum);


2 Answers

Use Calendar and set the current time then user the add method of the calendar

try this:

int noOfDays = 14; //i.e two weeks
Calendar calendar = Calendar.getInstance();
calendar.setTime(dateOfOrder);            
calendar.add(Calendar.DAY_OF_YEAR, noOfDays);
Date date = calendar.getTime();
like image 130
Rod_Algonquin Avatar answered Oct 10 '22 01:10

Rod_Algonquin


I will show you how we can do it in Java 8. Here you go:

public class DemoDate {
    public static void main(String[] args) {
        LocalDate today = LocalDate.now();
        System.out.println("Current date: " + today);

        //add 2 week to the current date
        LocalDate next2Week = today.plus(2, ChronoUnit.WEEKS);
        System.out.println("Next week: " + next2Week);
    }
}

The output:

Current date: 2016-08-15
Next week: 2016-08-29

Java 8 rocks !!

like image 26
PAA Avatar answered Oct 09 '22 23:10

PAA