[Q#23307324][A#23307365] How do I add 2 weeks to a Date in java?
https://stackoverflow.com/q/23307324
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: 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.
Answer
https://stackoverflow.com/a/23307365
Use Calendar and set the current time then user the add method of the calendar try this:
APIzation
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();
package com.stackoverflow.api;
import java.util.Calendar;
import java.util.Date;
public class Human23307365 {
public static Date addTwoWeeksToDate(Date dateOfOrder) {
int noOfDays = 14; //i.e two weeks
Calendar calendar = Calendar.getInstance();
calendar.setTime(dateOfOrder);
calendar.add(Calendar.DAY_OF_YEAR, noOfDays);
return calendar.getTime();
}
}
package com.stackoverflow.api;
import java.util.Calendar;
import java.util.Date;
import java.util.Date;
/**
* How do I add 2 weeks to a Date in java?
*
* @author APIzator
* @see <a href="https://stackoverflow.com/a/23307365">https://stackoverflow.com/a/23307365</a>
*/
public class APIzator23307365 {
public static Date addWeek(Date dateOfOrder, int noOfDays)
throws Exception {
Calendar calendar = Calendar.getInstance();
calendar.setTime(dateOfOrder);
calendar.add(Calendar.DAY_OF_YEAR, noOfDays);
return calendar.getTime();
}
}