This question already has answers here:
Android/Java - Date Difference in days
(18 answers)
Closed 6 years ago.
I need to calculate number of days between two dates and I am using below code. problem is it is returning me 2 but actually it should return 3 because difference between 30 june 2016 to 27 june is 3. can you please help where it should include current date as well in difference?
public static long getNoOfDaysBtwnDates(String expiryDate) {
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
Date expDate = null;
long diff = 0;
long noOfDays = 0;
try {
expDate = formatter.parse(expiryDate);
//logger.info("Expiry Date is " + expDate);
// logger.info(formatter.format(expDate));
Date createdDate = new Date();
diff = expDate.getTime() - createdDate.getTime();
noOfDays = TimeUnit.DAYS.convert(diff, TimeUnit.MILLISECONDS);
long a = TimeUnit.DAYS.toDays(noOfDays);
// logger.info("No of Day after difference are - " + TimeUnit.DAYS.convert(diff, TimeUnit.MILLISECONDS));
System.out.println(a);
System.out.println(noOfDays);
} catch (ParseException e) {
e.printStackTrace();
}
return noOfDays;
}
expiry date is 2016-06-30 and current date is 2016-06-27
Reason is, you are not subtracting two dates with same time format.
Use Calendar class to change the time as 00:00:00 for both date and you will get exact difference in days.
Date createdDate = new Date();
Calendar time = Calendar.getInstance();
time.set(Calendar.HOUR_OF_DAY, 0);
time.set(Calendar.MINUTE, 0);
time.set(Calendar.SECOND, 0);
time.set(Calendar.MILLISECOND, 0);
createdDate = time.getTime();
More explaination in Jim Garrison' answer
Why not use LocalDate?
import java.time.LocalDate;
import static java.time.temporal.ChronoUnit.DAYS;
long diffInDays(LocalDate a, LocalDate b) {
return DAYS.between(a, b);
}
The problem is that
Date createdDate = new Date();
sets createdDate to the current instant, that is, it includes the current time as well as the date. When you parse a string using the given format, the time is initialized to 00:00:00.
Let's say you ran this at exactly 18:00 local time, you end up with
createdDate = 2016-06-27 18:00:00.000
expDate = 2016-06-30 00:00:00.000
The difference is 2 days 6 hours, not 3 days.
You should be using the newer java.time.* classes from Java 8. There is a class LocalDate that represents dates without time-of-day. It includes methods for parsing using a format, and LocalDate.now() to get the current date, as well as methods for calculating intervals between LocalDate instances.
Using the Calendar.get(Calendar.DAY_OF_MONTH) as pointed out by python:
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
Date expDate = null;
String expiryDate ="2016-06-30";
int diff = 0;
try {
expDate = formatter.parse(expiryDate);
//logger.info("Expiry Date is " + expDate);
// logger.info(formatter.format(expDate));
Calendar cal = Calendar.getInstance();
int today = cal.get(Calendar.DAY_OF_MONTH);
cal.setTime(expDate);
diff = cal.get(Calendar.DAY_OF_MONTH)- today;
} catch (ParseException e) {
e.printStackTrace();
}
System.out.println(diff);
Related
This question already has answers here:
Calculating the difference between two Java date instances
(45 answers)
Closed 7 years ago.
I need to get difference between two dates using Java. I need my result to be in months and year of month.
Example:
Startdate = 2015-04-03 enddate = 2015-05-03 Result should be APR-MAY 2015
Startdate = 2015-12-03 enddate = 2015-01-03 Result should be DEC-2015,JAn-2016
i need to set that value into textview how can i set this plz help me .
String startdate = "2015-11-30";
String enddate = "2016-1-30";
DateFormat formater = new SimpleDateFormat("yyyy-MM-dd");
DateFormat outputFormater = new SimpleDateFormat("MMM-yyyy");
Calendar beginCalendar = Calendar.getInstance();
Calendar finishCalendar = Calendar.getInstance();
try {
beginCalendar.setTime(formater.parse(startdate));
finishCalendar.setTime(formater.parse(enddate));
if (beginCalendar.get(Calendar.MONTH) != finishCalendar.get(Calendar.MONTH)){
beginCalendar.set(Calendar.DAY_OF_MONTH, 1);
finishCalendar.set(Calendar.DAY_OF_MONTH, 2);
}
do {
// add one month to date per loop
String month_year = outputFormater.format(beginCalendar.getTime());
Log.d("Date_Range", month_year);
beginCalendar.add(Calendar.MONTH, 1);
} while (beginCalendar.before(finishCalendar));
} catch (ParseException e) {
e.printStackTrace();
}
So by this you will get month and year between start date and end date in MMM-yyyy format. You can handle the result in the way you want by splitting month_year string # "-" separator.
You can use SimpleDateFormat.
EDIT: Try this
SimpleDateFormat formatter = new SimpleDateFormat("yyyy");
Check if your dates are in the same year by getting the year of the calendar.
int year1=Integer.pareInt(formatter.format(calendar1.getTime()));
int year2=Integer.pareInt(formatter.format(calendar2.getTime()));
year=year1-year2;
and then print result based on the year
formatter=new SimpleDateFormat("MMM");
if(year==0)
System.out.println(formatter.format(calendar1)+"-"+formatter.format(calendar2)+" "+ year);
else
System.out.println(formatter.format(calendar1)+"-"+year1+","+formatter.format(calendar2)+"-"+year2);
This question already has answers here:
Calculating the difference between two Java date instances
(45 answers)
Closed 7 years ago.
i'm trying the get the Difference between 2 dates time..
i have an arraylist, each object contains data of type Date..
My Questions are:
1) is using Calendar.getInstance().get(Calendar.MINUTE) ... etc the best way to get the current date & Time
2) should i fill manually the data in variable of Date, as follows:
Date currentDate = new Date();
currentDate.setMinutes(Calendar.getInstance().get(Calendar.MINUTE));
currentDate.setHours(Calendar.getInstance().get(Calendar.HOUR));
currentDate.setDate(Calendar.getInstance().get(Calendar.DAY_OF_MONTH));
currentDate.setMonth(Calendar.getInstance().get(Calendar.MONTH));
currentDate.setYear(Calendar.getInstance().get(Calendar.YEAR));
3) How to get the Difference between the currentDate and the an old date i have
is it like currentDate - oldDate and what about the "AM_PM" issue, should i do this function manually?
1) is using Calendar.getInstance().get(Calendar.MINUTE) ... etc the best way to get the current date
JavaDoc from java.util.Date empty constructor:
Allocates a Date object and initializes it so that it represents the
time at which it was allocated, measured to the nearest millisecond.
3) How to get the Difference between the currentDate and the an old date i have is it like currentDate - oldDate and what about the "AM_PM" issue, should i do this function manually?
Date oldDate = ...
Date currentDate = new Date();
long dt = currentDate.getTime() - oldDate.getTime();
1) To get the current date:
Date = new Date();
2) TO set manually a Date it is better to work with a Calendar.
Calendar c = new GregorianCalendar();
c.set(Calendar.MONTH, 1);
c.set(Calendar.YEAR, 2015);
// ... and so on
Date date = c.getTime();
3) to calculate the distance in ms between two dates.
Date d1 = ....;
Date d2 = ....;
long distance = d1.getTime() - d2.getTime();
Try this, variable now below is current date.
String givenDate = "03/11/2015";
SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
try {
Date date = (Date)dateFormat.parseObject(givenDate);
Date now = new Date();
System.out.println(date);
System.out.println(now);
int diffInDays = (int)( (now.getTime() - date.getTime())
/ (1000 * 60 * 60 * 24) );
System.out.println(diffInDays);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
You can choose any format and add time or AM/PM, see more details of SimpleDateFormat. If you dont have string dates then you can directly use date variable shown above.
Cheers !!
This question already has answers here:
Modify the week in a Calendar
(4 answers)
Closed 5 years ago.
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.
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();
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 !!
Use Calendar
Date date = ...
Calendar c = Calendar.getInstance();
c.setTime(date);
c.add(Calendar.WEEK_OF_MONTH, 2);
date = c.getTime();
Try this to add two weeks.
long date = System.currentTimeMillis() + 14 * 24 * 3600 * 1000;
Date newDate = new Date(date);
if pass 14 to this addDate method it will add 14 to the current date and return
public String addDate(int days) throws Exception {
final DateFormat dateFormat1 = new SimpleDateFormat(
"yyyy/MM/dd HH:mm:ss");
Calendar c = Calendar.getInstance();
c.setTime(new Date()); // Now use today date.
c.add(Calendar.DATE, addDays); // Adding 5 days
return dateFormat1.format(c.getTime());
}
Using the Joda-Time library will be easier and will handle Daylight Saving Time, other anomalies, and time zones.
java.util.Date date = new DateTime( DateTimeZone.forID( "America/Denver" ) ).plusWeeks( 2 ).withTimeAtStartOfDay().toDate();
If you are on java 8 you can use new date time api http://docs.oracle.com/javase/8/docs/api/java/time/LocalDateTime.html#plusWeeks-long-
if you are on java 7 or more old version of java you should use old api http://docs.oracle.com/javase/8/docs/api/java/util/Calendar.html#add-int-int-
I have two dates
1) from_date: eg. 01/01/2010 (1st January 2010)
2) present_date: eg. 05/06/2011 (5th June 2011)
I want the third date as:
3) req_date: eg. 01/01/2011(1st January 2011)
Year should come from "present_date" and day and month should come from "from_date".
The dates which I mentioned are hardCoded.
In my code, I run a query to get these 2 dates.
Look into the Calendar class
http://www.java-examples.com/add-or-substract-days-current-date-using-java-calendar
Something like // Untested
Calendar cal=Calendar.getInstance();
cal.setTime(from_date);
Calendar cal2=Calendar.getInstance();
cal2.setTime(present_date);
Calendar cal3=Calendar.getInstance();
cal3.set(cal2.get(CALENDAR.YEAR),cal1.get(CALENDAR.MONTH),cal1.get(CALENDAR.DATE));
Date reg_date = cal3.getTime();
You can set individual fields of dates:
Date req_date = from_date;
req_date.setYear (present_date.getYear());
Or, if you're using Calendar (Date is deprecated):
Calendar req_date = from_date;
req_date.set (YEAR, present_date.get(YEAR));
If they're strings, you can just use substringing to get what you want:
String req_date = from_date.substring(0,6) + present_date.substring(6);
(assuming XX/XX/YYYY as seems to be the case).
Not sure if I understand you correctly but this example should get you started:
int year = 2003;
int month = 12;
int day = 12;
String date = year + "/" + month + "/" + day;
java.util.Date utilDate = null;
try {
SimpleDateFormat formatter = new SimpleDateFormat("yyyy/MM/dd");
utilDate = formatter.parse(date);
System.out.println("utilDate:" + utilDate);
} catch (ParseException e) {
System.out.println(e.toString());
e.printStackTrace();
}
this way you can convert date Strings to java.util.Date object, then you can construct the third date by using Date/Calendar methods
from_date: for EX. 01/01/2010 (1 st January 2010)
present_date :for EX. 05/06/2011(5th june 2011)
String s1[]=from_date.split("/");
String s2[]=present_date.split("/");
String newDate=s1[0]+"/"+s1[1]+"/"+s2[2];
import java.util.Date;
public class DateDemo {
public static void main(String args[]) {
Date date = new Date();
System.out.println(date.toString());
}
}
This question already has answers here:
How to compare dates in Java? [duplicate]
(11 answers)
Closed 9 years ago.
I have two dates:
toDate (user input in MM/dd/yyyy format)
currentDate (obtained by new Date())
I need to compare the currentDate with toDate. I have to display a report only when the toDate is equal to or more than currentDate. How can I do that?
It is easier to compare dates using the java.util.Calendar.
Here is what you might do:
Calendar toDate = Calendar.getInstance();
Calendar nowDate = Calendar.getInstance();
toDate.set(<set-year>,<set-month>,<set-day>);
if(!toDate.before(nowDate)) {
//display your report
} else {
// don't display the report
}
If you're set on using Java Dates rather than, say, JodaTime, use a java.text.DateFormat to convert the string to a Date, then compare the two using .equals:
I almost forgot: You need to zero out the hours, minutes, seconds, and milliseconds on the current date before comparing them. I used a Calendar object below to do it.
import java.text.DateFormat;
import java.util.Calendar;
import java.util.Date;
// Other code here
String toDate;
//toDate = "05/11/2010";
// Value assigned to toDate somewhere in here
DateFormat df = DateFormat.getDateInstance(DateFormat.SHORT);
Calendar currDtCal = Calendar.getInstance();
// Zero out the hour, minute, second, and millisecond
currDtCal.set(Calendar.HOUR_OF_DAY, 0);
currDtCal.set(Calendar.MINUTE, 0);
currDtCal.set(Calendar.SECOND, 0);
currDtCal.set(Calendar.MILLISECOND, 0);
Date currDt = currDtCal.getTime();
Date toDt;
try {
toDt = df.parse(toDate);
} catch (ParseException e) {
toDt = null;
// Print some error message back to the user
}
if (currDt.equals(toDt)) {
// They're the same date
}
Date#equals() and Date#after()
If there is a possibility that the hour and minute fields are != 0, you'd have to set them to 0.
I can't forget to mention that using java.util.Date is considered a bad practice, and most of its methods are deprecated. Use java.util.Calendar or JodaTime, if possible.
You are probably looking for:
!toDate.before(currentDate)
before() and after() test whether the date is strictly before or after. So you have to take the negation of the other one to get non strict behaviour.
This is one of the ways:
String toDate = "05/11/2010";
if (new SimpleDateFormat("MM/dd/yyyy").parse(toDate).getTime() / (1000 * 60 * 60 * 24) >= System.currentTimeMillis() / (1000 * 60 * 60 * 24)) {
System.out.println("Display report.");
} else {
System.out.println("Don't display report.");
}
A bit more easy interpretable:
String toDateAsString = "05/11/2010";
Date toDate = new SimpleDateFormat("MM/dd/yyyy").parse(toDateAsString);
long toDateAsTimestamp = toDate.getTime();
long currentTimestamp = System.currentTimeMillis();
long getRidOfTime = 1000 * 60 * 60 * 24;
long toDateAsTimestampWithoutTime = toDateAsTimestamp / getRidOfTime;
long currentTimestampWithoutTime = currentTimestamp / getRidOfTime;
if (toDateAsTimestampWithoutTime >= currentTimestampWithoutTime) {
System.out.println("Display report.");
} else {
System.out.println("Don't display report.");
}
Oh, as a bonus, the JodaTime's variant:
String toDateAsString = "05/11/2010";
DateTime toDate = DateTimeFormat.forPattern("MM/dd/yyyy").parseDateTime(toDateAsString);
DateTime now = new DateTime();
if (!toDate.toLocalDate().isBefore(now.toLocalDate())) {
System.out.println("Display report.");
} else {
System.out.println("Don't display report.");
}
Date long getTime() returns the number of milliseconds since January 1, 1970, 00:00:00 GMT represented by this Date object.
//test if date1 is before date2
if(date1.getTime() < date2.getTime()) {
....
}
private boolean checkDateLimit() {
long CurrentDateInMilisecond = System.currentTimeMillis(); // Date 1
long Date1InMilisecond = Date1.getTimeInMillis(); //Date2
if (CurrentDateInMilisecond <= Date1InMilisecond) {
return true;
} else {
return false;
}
}
// Convert both date into milisecond value .
If for some reason you're intent on using Date objects for your solution, you'll need to do something like this:
// Convert user input into year, month, and day integers
Date toDate = new Date(year - 1900, month - 1, day + 1);
Date currentDate = new Date();
boolean runThatReport = toDate.after(currentDate);
Shifting the toDate ahead to midnight of the next day will take care of the bug I've whined about in the comments to other answers. But, note that this approach uses a deprecated constructor; any approach relying on Date will use one deprecated method or another, and depending on how you do it may lead to race conditions as well (if you base toDate off of new Date() and then fiddle around with the year, month, and day, for instance). Use Calendar, as described elsewhere.
Use java.util.Calendar if you have extensive date related processing.
Date has before(), after() methods. you could use them as well.