This question already has answers here:
Java, Calculate the number of days between two dates [duplicate]
(10 answers)
Closed 7 years ago.
I have noted error in bellow code when trying calculate days between two dates. There isn't right with month February,
Here is code,
public class NewClass {
public int numberOfDays(String fromDate,String toDate)
{
java.util.Calendar cal1 = new java.util.GregorianCalendar();
java.util.Calendar cal2 = new java.util.GregorianCalendar();
StringBuffer sBuffer = new StringBuffer(fromDate);
String yearFrom = sBuffer.substring(6,10);
String monFrom = sBuffer.substring(0,2);
String ddFrom = sBuffer.substring(3,5);
int intYearFrom = Integer.parseInt(yearFrom);
int intMonFrom = Integer.parseInt(monFrom);
int intDdFrom = Integer.parseInt(ddFrom);
cal1.set(intYearFrom, intMonFrom, intDdFrom);
StringBuffer sBuffer1 = new StringBuffer(toDate);
String yearTo = sBuffer1.substring(6,10);
String monTo = sBuffer1.substring(0,2);
String ddTo = sBuffer1.substring(3,5);
int intYearTo = Integer.parseInt(yearTo);
int intMonTo = Integer.parseInt(monTo);
int intDdTo = Integer.parseInt(ddTo);
cal2.set(intYearTo, intMonTo, intDdTo);
int days = daysBetween(cal1.getTime(),cal2.getTime());
return days;
}
public int daysBetween(Date d1, Date d2)
{
return (int)( (d2.getTime() - d1.getTime()) / (1000 * 60 * 60 * 24));
}
public static void main(String[] args) throws ParseException {
String s1 = "02-28-2015";
String s2 = "03-01-2015";
int num=numberOfDays(s1, s2);
System.out.println(num);
}
}
If we gives above dates for varialbe s1 and s2, result is 4. But answer is wrong
because 2015 February has only 28 days.
I think problem is this function part (1000 * 60 * 60 * 24)
If anyone knows what to do with this, please update this code or give me some help!!!
Don't ever try and use the millisecond difference between two times to calculate the differences, there are just to many idiosyncrasies with date/time calculations which can cause all sorts of erroneous errors.
Instead, save yourself (alot) of time and use a dedicated library
Java 8
LocalDate start = LocalDate.of(2015, Month.JANUARY, 1);
LocalDate end = LocalDate.now();
long days = ChronoUnit.DAYS.between(start, end);
System.out.println(days);
Which outputs 69
JodaTime
DateTime startDate = new DateTime(2015, DateTimeConstants.JANUARY, 1, 0, 0);
DateTime endDate = new DateTime();
Days d = Days.daysBetween(startDate, endDate);
int days = d.getDays();
System.out.println(days);
Which outputs 69
Related
This question already has answers here:
new Date() to Julian date format in java
(3 answers)
Closed 7 years ago.
I need to store a day as an int and then periodically compare it to today as an int.
if(today - trialStartDay > 30)...
I've come across the Julian Day in my research and that seems like a fine standard to use, but I'm not sure how to get it in Android/Java. I'm looking at Calendar/Date/JodaTime and am just getting confused. This seems like it should be very simple. Any advice? Thanks.
one possibility without using third part libraries:
#Test
public void julianDateTest() {
Date lDate = new Date();
Calendar lCal = Calendar.getInstance();
lCal.setTime(lDate);
int lYear = lCal.get(Calendar.YEAR);
int lMonth = lCal.get(Calendar.MONTH) + 1;
int lDay = lCal.get(Calendar.DATE);
int a = (14 - lMonth) / 12;
int y = lYear + 4800 - a;
int m = lMonth + 12 * a - 3;
Integer lJulianDate = lDay + (153 * m + 2) / 5 + 365 * y + y / 4 - y / 100 + y / 400 - 32045;
Assert.assertTrue(lJulianDate>0);
}
for today 24-11-2014 the output would be:
2457351
A part of code with multiple examples :
(Ask me in comment if you don't understand)
public static String getFriendlyDayString(Context context, long dateInMillis) {
// The day string for forecast uses the following logic:
// For today: "Today, June 8"
// For tomorrow: "Tomorrow"
// For the next 5 days: "Wednesday" (just the day name)
// For all days after that: "Mon Jun 8"
Time time = new Time();
time.setToNow();
long currentTime = System.currentTimeMillis();
int julianDay = Time.getJulianDay(dateInMillis, time.gmtoff);
int currentJulianDay = Time.getJulianDay(currentTime, time.gmtoff);
// If the date we're building the String for is today's date, the format
// is "Today, June 24"
if (julianDay == currentJulianDay) {
String today = context.getString(R.string.today);
int formatId = R.string.format_full_friendly_date;
return String.format(context.getString(
formatId,
today,
getFormattedMonthDay(context, dateInMillis)));
} else if ( julianDay < currentJulianDay + 7 ) {
// If the input date is less than a week in the future, just return the day name.
return getDayName(context, dateInMillis);
} else {
// Otherwise, use the form "Mon Jun 3"
SimpleDateFormat shortenedDateFormat = new SimpleDateFormat("EEE MMM dd");
return shortenedDateFormat.format(dateInMillis);
}
I am trying to make a method that will calculate the age of a person. I want the calculation to be done under the second public static int getAge. If the person is born after the current date i want it to print out error -1.
How do I compare the two SimpleDate values dateBd and dateRef in order to get an int value for age?
public static SimpleDate today() {
Calendar todayCal = Calendar.getInstance();
SimpleDate todayDate = new SimpleDate();
todayDate.setDate(todayCal.get(Calendar.MONTH) + 1,
todayCal.get(Calendar.DATE),
todayCal.get(Calendar.YEAR));
return todayDate;
public static int getAge(SimpleDate dateBd) {
int age;
SimpleDate dateToday = today();
age = getAge(dateBd, dateToday);
return age;
public static int getAge(SimpleDate dateBd, SimpleDate dateRef) {
if(getAge(dateBd)>getAge(dateRef)){
system.out.println("error");
}
return -1;
What is SimpleDate ? Anyway here something to get you started
import java.util.GregorianCalendar;
import java.util.Calendar;
public class CalcAge {
public static void main(String [] args) {
// remember ... months are 0-based : jan=0 feb=1 ...
System.out.println
("1962-11-11 : " + age(1962,10,11));
System.out.println
("1999-12-03 : " + age(1999,11,3));
}
private static int age(int y, int m, int d) {
Calendar cal = new GregorianCalendar(y, m, d);
Calendar now = new GregorianCalendar();
int res = now.get(Calendar.YEAR) - cal.get(Calendar.YEAR);
if((cal.get(Calendar.MONTH) > now.get(Calendar.MONTH))
|| (cal.get(Calendar.MONTH) == now.get(Calendar.MONTH)
&& cal.get(Calendar.DAY_OF_MONTH) > now.get(Calendar.DAY_OF_MONTH)))
{
res--;
}
return res;
}
}
Don't ever try and use the millisecond difference between two times to calculate the differences, there are just to many idiosyncrasies with date/time calculations which can cause all sorts of erroneous errors.
Instead, save yourself (alot) of time and use a dedicated library
Java 8
LocalDate start = LocalDate.of(1972, Month.MARCH, 8);
LocalDate end = LocalDate.now();
long years = ChronoUnit.YEARS.between(start, end);
System.out.println(years);
Which outputs 43
JodaTime
DateTime startDate = new DateTime(1972, DateTimeConstants.MARCH, 8, 0, 0);
DateTime endDate = new DateTime();
Years y = Years.yearsBetween(startDate, endDate);
int years = y.getYears();
System.out.println(years );
Which outputs 43
You can even use a Period to gain more granuarlity...
Period period = new Period(startDate, endDate);
PeriodFormatter hms = new PeriodFormatterBuilder()
.printZeroAlways()
.appendYears()
.appendSeparator(" years, ")
.appendMonths()
.appendSeparator(" months, ")
.appendDays()
.appendLiteral(" days")
.toFormatter();
String result = hms.print(period);
System.out.println(result);
Which prints 43 years, 1 months, 5 days
LocalDate date1 = new LocalDate(2015, 3, 22);
LocalDate date2 = new LocalDate(2015, 9, 30);
PeriodType monthDay = PeriodType.yearMonthDay().withYearsRemoved();
Period difference = new Period(date1, date2, monthDay);
int months = difference.getMonths();
int days = difference.getDays();
int alertMonth = 2;
int intervalLoop = date2.getMonthOfYear() / alertMonth ;
for(int i=date1.getMonthOfYear();i<date2.getMonthOfYear();i++){
int intervalTime = i * alertMonth;
if(intervalTime >13){
return;
}else{
LocalDate d = getNDayOfMonth( DateTimeConstants.WEDNESDAY, 2, i, 2015);
System.out.println("month----> "+i+" "+d);
This code may help..
DateTime urDate = DateTime(date); //Your Date time
DateTime afterThreeMonths = urDate.plusMonths(6); //Add 3 months to your Date
afterThreeMonths.withDayOfWeek(DateTimeConstants.MONDAY); //Find next monday
afterThreeMonths.plusWeeks(2); //Add two more weeks to the first monday.
NB: I never run this code. Try and find it out urself.
I've actually been browsing for quite a while on this site, sadly without much progress. Thanks to a lot of extremely useful answers, I've learned quite a bunch of stuff though!
I'm learning Java since ... about 4 days (I guess?) so I'm not very experienced in the methods I can use.
There's this assignment we got at our univ. We shall write a program that returns how many days have passed between two dates. The only restriction is to keep the program as simple as possible, we're not allowed to use "complicated methods".
Sadly, my program is kind of stuck. If I try it out e.g. the dates 23 01 1994 and 07 04 1997, it counts only up to 01 01 1997 and suddenly stops. I have no idea why that happens, I even doubt if I fully understood what I wrote there.
Anyways, here's my code:
import java.util.Arrays;
import java.util.Scanner;
public class Datecalc {
public static int yearcounter,monthcounter,daycounter,days;
public static int[] input() {
Scanner input = new Scanner(System.in);
//Eingabe der Daten
String day1 = input.next();
String month1 = input.next();
String year1 = input.next();
String day2 = input.next();
String month2 = input.next();
String year2 = input.next();
int day1int = Integer.parseInt(day1);
int month1int = Integer.parseInt(month1);
int year1int = Integer.parseInt(year1);
int day2int = Integer.parseInt(day2);
int month2int = Integer.parseInt(month2);
int year2int = Integer.parseInt(year2);
int [] eingabe = new int [6];
eingabe[0] = day1int;
eingabe[1] = month1int;
eingabe[2] = year1int;
eingabe[3] = day2int;
eingabe[4] = month2int;
eingabe[5] = year2int;
return eingabe;
// put everything into an array to be able to use it in the main method
}
public static void main(String[] args) {
int[] eingabe = input();
days=0;
daycounter = eingabe[0];
monthcounter = eingabe[1];
yearcounter = eingabe[2];
Integer[] einunddreissig = {1,3,5,7,8,10,12}; //months with 31 days
Integer[] dreissig = {4,6,9,11}; // months with 30 days
while (daycounter != eingabe[3] && monthcounter != eingabe[4] && yearcounter != eingabe[5] ) {
// if its a month that has 31 days
if ( Arrays.asList(einunddreissig).contains(monthcounter) ) {
for (int i = daycounter; i <= 31; i++) {
days++;
}
daycounter=1;
monthcounter++;
}
// if its a month with 30 days
if ( Arrays.asList(dreissig).contains(monthcounter) ) {
for (int i = daycounter; i <= 30; i++) {
days++;
daycounter++;
}
daycounter=1;
monthcounter++;
// february
} else if ( monthcounter == 2) {
for (int i = daycounter; i <= 28; i++) {
days++;
}
daycounter=1;
monthcounter++;
} else if (monthcounter==13) {
monthcounter=1;
yearcounter++;
}
}
// checking how many days were counted and comparing the input (eingabe[something]) to how far the daycounter reached
System.out.println(" "+days);
System.out.println(" "+daycounter+" "+monthcounter+" "+yearcounter);
System.out.println(eingabe[3]+" "+eingabe[4]+" "+eingabe[5]);
}
}
I hope there is somebody who might be so kind to give me a hint how to fix that.
I would separate this out into two different functions, one that counts the days until the end of the current year and another which counts the days since the beginning of the current year. Then you can put the total days in terms of those values.
First write a generic sum() function:
public static int sum(int[] a, int start, int end){
int sum = 0;
for(int i = start; i < end; i++) sum += a[i];
return sum;
}
Then use the sum() function to easily compute daysToEnd and daysFromStart:
static int[] daysInMonth = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
public static int daysToEnd(int day, int month){
return sum(daysInMonth, month - 1, 12) - day;
}
public static int daysFromStart(int day, int month){
return sum(daysInMonth, 0, month - 1) + day;
}
public static void main(String... args){
int[] date1 = {23, 1, 1994};
int[] date2 = {1, 1, 1997};
// This actually works for same or different years
int days = daysToEnd(date1[0], date1[1]) +
365*(date2[2] - date1[2] - 1) +
daysFromStart(date2[0], date2[1]);
System.out.println(days);
}
Do you have to use loops? Here's some food for thought -- imagine this as a simple algebra problem. In your program, each date is modeled as a collection of quantities, each of a different unit. Once you obtain uniform units, you can just do the arithmetic.
In the UNIX world we use an agreed-upon reference date called the "epoch", 12:00 AM on 01 January, 1970 as a reference date. Kind of like "tare" on a balance. All other dates can be represented as some number of seconds relative to that time.
I would construct the passed in user input to java.util.Date type. But I am assuming line by line input. You can construct a string using StringBuilder if you want to get day,mth,year separately.
try{
BufferedReader br = new BufferedReader(
new InputStreamReader(System.in));
DateFormat df = new SimpleDateFormat ("dd/MM/yyyy");
System.out.println("Enter Date1");
String dateSt1= br.readLine(); // Accepts date1 as string
System.out.println("Enter Date2");
String dateSt2= br.readLine(); // Accepts date2 as string
Date date1=df.parse(dateSt1); // Date String to Date
Date date2=df.parse(dateSt2);
}catch(IOException ex)
}catch(ParseExceptionOfSomesort pex)
}
then use this to get the difference in days -
int diffInDays = (int)( (date2.getTime() - date1.getTime())
/ (1000 * 60 * 60 * 24) )
If you get this in negative, that means the second date is before first date.
Think: Do I have to do it using a loop or hasn't java already added some utility method to do date compare?
What makes something "complicated" though? Writing too many lines of code or using existing java library?
I could use some help with this method I'm trying to make. I have a Problem Object, which has a target date and i need to find out how many days this problem is late divided/split by months, compared to today's date.
Image this situation:
Lets say that today's date is 05-02-2013.
ID Target date
P1 02-02-2013
P2 27-01-2013
P3 26-01-2013
P4 05-12-2012
This means that each problem is this many days late in the following months:
DEC JAN FEB
P1 3
P2 4 5
P3 5 5
P4 26 31 5
A problem can not be older than 12 months.
Now i need a method to sum these numbers storing the month name and a summed number of late days. If the target month and now month are the same, its an easy case, because i can just substract the days and store the month, but what to do when its not the case? I have the following code:
List<Problem> problems = problemQuery.getResultList(); //Problems list is already filtered and contain only late problems.
Calendar now = Calendar.getInstance();
Calendar before = Calendar.getInstance();
Map<Integer, Integer> newMap = new TreeMap<Integer, Integer>(); //map that contains month number and daysLateCount
for (Problem p : problems) {
before.setTime(p.getTarget_date());
int nowMonth = now.get(Calendar.MONTH);
int beforeMonth = before.get(Calendar.MONTH);
if (beforeMonth == nowMonth) { //easy case when both dates have same month
int result = now.get(Calendar.DAY_OF_MONTH) - before.get(Calendar.DAY_OF_MONTH);
if (newMap.containsKey(nowMonth)) {
int newLateDaysValue = newMap.get(nowMonth)+result; //get old result and add the new
newMap.put(nowMonth, newLateDaysValue);
}
else {
newMap.put(nowMonth, result);
}
}
else {
//What to do here???
}
}
Perhaps i could even skip the if-else clause and make an algorithm that could handle both cases? I don't know please help :)
The best way is to use Joda Time library: http://www.joda.org/joda-time/
Java Date/Time API is not very good and useful for such purposes.
I think there is a relatively simple solution to this, the algorithm is as follows:
import java.util.Calendar;
public class test {
public static void main(String[] args){
Calendar today = Calendar.getInstance();
Calendar problemDate = Calendar.getInstance();
today.set(2013, 01, 05);
problemDate.set(2012, 11, 05);
System.out.println(today.getTime());
System.out.println(problemDate.getTime());
// This might need further validation to make sure today >= problemDate
int diffYear = today.get(Calendar.YEAR) - problemDate.get(Calendar.YEAR);
int differenceInMonths = diffYear * 12 + today.get(Calendar.MONTH) - problemDate.get(Calendar.MONTH);
//int differenceInMonths = today.get(Calendar.MONTH) - problemDate.get(Calendar.MONTH);
for(int i = 0; i <= differenceInMonths; i++) {
int daysDifference;
if (differenceInMonths == 0) {
daysDifference = today.get(Calendar.DAY_OF_MONTH) - problemDate.get(Calendar.DAY_OF_MONTH);
} else {
if ( i == 0) { // first month
daysDifference = problemDate.getActualMaximum(Calendar.DAY_OF_MONTH) - problemDate.get(Calendar.DAY_OF_MONTH);
}
else if( i == differenceInMonths ) { // last month
daysDifference = today.get(Calendar.DAY_OF_MONTH);
}
else {
Calendar cal= Calendar.getInstance();
cal.set(Calendar.MONTH, problemDate.get(Calendar.MONTH) + i);
daysDifference = cal.getActualMaximum(Calendar.DAY_OF_MONTH);
}
}
System.out.println(daysDifference);
}
}
}
Which outputs:
Tue Feb 05 14:35:43 GMT 2013
Wed Dec 05 14:35:43 GMT 2012
26
31
5
You should be able to wrap this up into your code, and in a loop fairly easily, and also remove the print statements to insert into whatever data structure you have.
A solution using Joda-Time:
LocalDate today = new LocalDate(2013, 2, 5);
LocalDate targetDate = new LocalDate(2012, 12, 5); // example with target date P4
LocalDate begin = targetDate;
LocalDate end = begin.dayOfMonth().withMaximumValue();
while (end.isBefore(today)) {
Days days = Days.daysBetween(begin, end);
if (days.getDays() > 0) {
System.out.println(end.monthOfYear().getAsText() + ": " + days.getDays());
}
begin = end;
end = begin.plusDays(1).dayOfMonth().withMaximumValue();
}
end = today;
Days days = Days.daysBetween(begin, end);
if (days.getDays() > 0) {
System.out.println(end.monthOfYear().getAsText() + ": " + days.getDays());
}
Prints the following result for e.g. target date P4:
December: 26
January: 31
February: 5
The year is needed, if only to know how many days are in February.
for (Problem p : problems) {
int nowYear = now.get(Calendar.YEAR);
int nowMonth = now.get(Calendar.MONTH);
int nowDay = now.get(Calendar.DAY_OF_MONTH);
before.setTime(p.getTarget_date());
int beforeYear = before.get(Calendar.YEAR);
int beforeMonth = before.get(Calendar.MONTH);
int beforeDay = before.get(Calendar.DAY_OF_MONTH);
while (beforeYear < nowYear || beforeMonth < nowMonth) {
int daysInMonth =
before.getActualMaximum(Calendar.DAY_OF_MONTH);
int result = daysInMonth - beforeDay;
Integer oldLateDaysValue = newMap.get(beforeMonth);
newMap.put(beforeMonth,
oldLateDaysValue == null ?
result : (oldLateDaysValue + result));
// For all subsequent months, calculate using entire month.
beforeDay = 0;
before.add(Calendar.MONTH, 1);
beforeYear = before.get(Calendar.YEAR);
beforeMonth = before.get(Calendar.MONTH);
}
int result = nowDay - beforeDay;
Integer oldLateDaysValue = newMap.get(beforeMonth);
newMap.put(beforeMonth,
oldLateDaysValue == null ?
result : (oldLateDaysValue + result));
}
System.out.println(newMap);
}