Find number of days, weeks, months and year between two milliseconds.

5.4k views Asked by At

I need to set events in my custom calender which will repeat according to selected period i.e, daily, weekly, monthly or yearly. I have start and end dates in milliseconds.

Question:

Is there any Calender or Date API from which we can calculate number of days, weeks, months and year between two milliseconds. I used Joda library but not getting any appropriate method for this.

Should I had to write custom code for this ? :-(

8

There are 8 answers

0
Akhilesh Mani On BEST ANSWER

I create a custom code for this task. Here you will find future date of events which is set between any two timestamps (start timestamp should be less or equal to end timestamp). You has to fix event duration like weekly,yearly,daily or monthly .

    public class EventManipulationClass {

   public EventManipulationClass(){
        for (int i = 0; i < MyPetApplication.instance.eventDatasArrayList.size(); i++) {
            String repType=MyPetApplication.instance.eventDatasArrayList.get(i).getRepeat();
            if (repType.equals("Daily")) {
                computeDaily(<long startTimeMilliSeconds>,<long endTimeMilliSeconds>);
            } else if (repType.equals("Yearly")) {
                computeYearly(<long startTimeMilliSeconds>,<long endTimeMilliSeconds>);
            } else if (repType.equals("Monthly")) {
                computeMonthly(<long startTimeMilliSeconds>,<long endTimeMilliSeconds>);
            } else if (repType.equals("Weekly")) {
                computeWeekely(<long startTimeMilliSeconds>,<long endTimeMilliSeconds>);
            } else {
                <none>
            }
        }
    }

   private String doubleDigitDate(int date){
       String tempDate;
        if(date<10){
            tempDate="0"+date;
        }else {
            tempDate=""+date;
        }
        return tempDate;
   }

    private void computeWeekely(long starT,long endT){
        int sMonth;
        int sYear;
        int sDay;

        int eMonth;
        int eYear;
        int eDay;

        int diffMonth;
        int diffYear;

        Calendar startCalendar=GregorianCalendar.getInstance();
        startCalendar.setTimeInMillis(starT);
        sMonth=startCalendar.get(Calendar.MONTH)+1;
        sDay=startCalendar.get(Calendar.DAY_OF_MONTH);
        sYear=startCalendar.get(Calendar.YEAR);

        Calendar endCalendar=GregorianCalendar.getInstance();
        endCalendar.setTimeInMillis(endT);
        eMonth=endCalendar.get(Calendar.MONTH)+1;
        eDay=endCalendar.get(Calendar.DAY_OF_MONTH);
        eYear=endCalendar.get(Calendar.YEAR);

        diffMonth=eMonth-sMonth;
        diffYear=eYear-sYear;

        if(diffMonth==0 && diffYear==0){
            int eventDate = sDay;
            int totalDaysInMonth = getNumberOfDaysInMonth(sMonth, (sYear % 400 == 0) ? true:false);
            boolean isLastDay = false;
            for (int x2 = 0; x2 <= 5; x2++) {
                if (eventDate <= totalDaysInMonth && eventDate <= eDay) {
                    System.out.println("same month same year 1=====> "+ sMonth+ "-" + eventDate + "-"+ sYear);
                    if(eventDate==eDay){
                            isLastDay=true;
                            break;
                        } else {
                            eventDate=eventDate+7;
                            continue;                               
                        }
                 }else { 
                     if (isLastDay) {
                            break;
                        }else{
                            System.out.println("same month same year 2 =====> "+ eMonth+ "-" + eDay + "-"+ eYear);
                            break;
                        }   
                 }
                }
        } else if(diffMonth!=0 && diffYear==0){
        int eventDate = 0;
        int totalDaysInMonth = 0;
        @SuppressWarnings("unused")
        boolean isLastDay = false;
        for (int x = sMonth; x <= eMonth; x++) {
            if(x==sMonth){
                  eventDate=sDay;
            }else{
                  eventDate=Math.abs(eventDate-totalDaysInMonth);
            }
            totalDaysInMonth=getNumberOfDaysInMonth(x, (sYear % 400 == 0) ? true:false);
            for (int x2 = 0; x2 <= 5; x2++) {
             if (eventDate <= totalDaysInMonth) {
                 if(x==eMonth && eventDate >eDay){
                    System.out.println("Diff month same year 1 =====> "+ x+ "-" + eDay + "-"+ sYear);
                    isLastDay=true;
                    break;
                }else {
                    System.out.println("Diff month same year 2 =====> "+ x+ "-" + eventDate + "-"+ sYear);
                    if(x==eMonth && eventDate ==eDay){
                            isLastDay=true;
                            break;
                        } else {
                            eventDate=eventDate+7;
                            continue;                               
                    }
                }
            } else {
                break;
            }
        }
        }
    }else  { 
            int numberOfYear = Math.abs(sYear - eYear) ;
            Integer yearsArray[] = new Integer[numberOfYear+1];
            int eventDate = 0;
            for (int i = 0; i <= numberOfYear; i++) {
                yearsArray[i] = sYear + i;
            }
            int totalDaysInMonth = 0;
            for (int j = 0; j < yearsArray.length ; j++) {
                if (j == 0) {
                    for (int x = sMonth; x <= 12; x++) {
                        if(x==sMonth){
                              eventDate=sDay;
                        }else{
                              eventDate=Math.abs(eventDate-totalDaysInMonth);
                        }
                        totalDaysInMonth=getNumberOfDaysInMonth(x, (sYear % 400 == 0) ? true:false);
                        for (int x2 = 0; x2 <= 5; x2++) {
                            if (eventDate <= totalDaysInMonth) {
                                System.out.println("Diff month Diff year 1=====> "+ x+ "-" + eventDate + "-"+ sYear);
                                eventDate=eventDate+7;
                            } else {
                                break;
                            }
                        }
                    }
                } else if (j < yearsArray.length-1) {
                    for (int x = 1; x <= 12; x++) {
                        eventDate=Math.abs(eventDate-totalDaysInMonth);
                        totalDaysInMonth=getNumberOfDaysInMonth(x, (sYear % 400 == 0) ? true:false);

                        for (int x2 = 0; x2 <= 5; x2++) {
                            if (eventDate <= totalDaysInMonth) {
                                System.out.println("Diff month Diff year 2=====> "+ x+ "-" + eventDate + "-"+ yearsArray[j]);
                                eventDate=eventDate+7;
                            } else {
                                break;
                            }
                        }
                    }
                } else {
                    for (int x = 1; x <= eMonth; x++) {
                        eventDate=Math.abs(eventDate-totalDaysInMonth);
                        totalDaysInMonth=getNumberOfDaysInMonth(x, (sYear % 400 == 0) ? true:false);

                        for (int x2 = 0; x2 <= 5; x2++) {
                            if (eventDate <= totalDaysInMonth) {
                                if(x==eMonth && eventDate >eDay){
                                    System.out.println("Diff month Diff year 3 1=====> "+ x+ "-" + eDay + "-"+ yearsArray[j]);
                                    break;
                                }else {
                                    System.out.println("Diff month Diff year 3 2=====> "+ x+ "-" + eventDate + "-"+ yearsArray[j]);

                                    if(x==eMonth && eventDate >eDay){
                                        System.out.println("Diff month Diff year 3 1.2=====> "+ x+ "-" + eDay + "-"+ yearsArray[j]);
                                    break;
                                    } else {
                                        eventDate=eventDate+7;
                                        continue;
                                    }
                                }
                            } else {
                                if(x==eMonth && eventDate >eDay){
                                    System.out.println("Diff month Diff year 3 1.2=====> "+ x+ "-" + eDay + "-"+ yearsArray[j]);
                                    break;
                                    }
                                break;
                            }
                        }
                    }
                }
            }
        }
    }

    private void computeDaily(long starT,long endT){
        int sMonth;
        int sYear;
        int sDay;

        int eMonth;
        int eYear;
        int eDay;

        int diffMonth;
        int diffYear;

        Calendar startCalendar=GregorianCalendar.getInstance();
        startCalendar.setTimeInMillis(starT);
        sMonth=startCalendar.get(Calendar.MONTH)+1;
        sDay=startCalendar.get(Calendar.DAY_OF_MONTH);
        sYear=startCalendar.get(Calendar.YEAR);

        Calendar endCalendar=GregorianCalendar.getInstance();
        endCalendar.setTimeInMillis(endT);
        eMonth=endCalendar.get(Calendar.MONTH)+1;
        eDay=endCalendar.get(Calendar.DAY_OF_MONTH);
        eYear=endCalendar.get(Calendar.YEAR);

        diffMonth=eMonth-sMonth;
        diffYear=eYear-sYear;

        if(diffMonth==0 && diffYear==0){
            for (int i = sDay; i <= eDay; i++) {
                System.out.println("same month same year 1=====> "+ sMonth+ "-" + i + "-"+ sYear);
            }
            }
        else if (diffMonth != 0 && diffYear == 0) {
            int totalDaysInMonth = 0;
            for (int x = sMonth; x <= eMonth; x++) {
                if(x==sMonth){
                    totalDaysInMonth=getNumberOfDaysInMonth(x, (sYear % 400 == 0) ? true:false);
                    for (int i = sDay; i <= totalDaysInMonth; i++) {
                        System.out.println("Diff month same year 1=====> "+ x+ "-" + i + "-"+ sYear);
                    }
                }else if(x==eMonth){
                    for (int i = 1; i <= eDay; i++) {
                        System.out.println("Diff month same year 1=====> "+ x+ "-" + i + "-"+ sYear);
                    }
                }
                else {
                    totalDaysInMonth = getNumberOfDaysInMonth(x, (sYear % 400 == 0) ? true:false);
                    for (int i = 1; i <= totalDaysInMonth; i++) {
                        System.out.println("Diff month same year 1=====> "+ x+ "-" + i + "-"+ sYear);
                    }
                }
            }

        }else  { 
            int numberOfYear = Math.abs(sYear - eYear) ;
            Integer yearsArray[] = new Integer[numberOfYear+1];
            for (int i = 0; i <= numberOfYear; i++) {
                yearsArray[i] = sYear + i;
            }
            int totalDaysInMonth = 0;
            for (int j = 0; j < yearsArray.length ; j++) {
                System.out.println(">>>>>>>>> J" +j+">>>>>>>>"+yearsArray.length);
                if (j == 0) {
                    for (int x = sMonth; x <= 12; x++) {
                        if(x == sMonth){
                            totalDaysInMonth=getNumberOfDaysInMonth(x, (sYear % 400 == 0) ? true:false);
                            for (int i = sDay; i <= totalDaysInMonth; i++) {
                                System.out.println("Diff month Diff year 1=====> "+ x+ "-" + i + "-"+ sYear);
                            }
                        }else {
                            totalDaysInMonth = getNumberOfDaysInMonth(x, (sYear % 400 == 0) ? true:false);
                            for (int i = 1; i <= totalDaysInMonth; i++) {
                                System.out.println("Diff month Diff year 1=====> "+ x+ "-" + i + "-"+ sYear);
                            }
                        }
                    }
                } else if (j < yearsArray.length-1) {
                    for (int x = 1; x <= 12; x++) {
                        totalDaysInMonth = getNumberOfDaysInMonth(x, (sYear % 400 == 0) ? true:false);
                        for (int i = 1; i <= totalDaysInMonth; i++) {
                            System.out.println("Diff month Diff year 1=====> "+ x+ "-" + i + "-"+ yearsArray[j]);
                        }
                    }
                } else {
                    for (int x = 1; x <= eMonth; x++) {
                        totalDaysInMonth = getNumberOfDaysInMonth(x, (sYear % 400 == 0) ? true:false);
                        if(x==eMonth){
                            for (int i = 1; i <= eDay; i++) {
                                System.out.println("Diff month Diff year 1=====> "+ x+ "-" + i + "-"+ yearsArray[j]);
                            }
                        }else {
                            for (int i = 1; i <= totalDaysInMonth; i++) {
                                System.out.println("Diff month Diff year 1=====> "+ x+ "-" + i + "-"+ yearsArray[j]);
                            }
                        }
                    }
                }
            }
        }
    }

    private void computeMonthly(long starT,long endT){
        int sMonth;
        int sYear;
        int sDay;

        int eMonth;
        int eYear;

        int diffMonth;
        int diffYear;

        Calendar startCalendar=GregorianCalendar.getInstance();
        startCalendar.setTimeInMillis(starT);
        sMonth=startCalendar.get(Calendar.MONTH)+1;
        sDay=startCalendar.get(Calendar.DAY_OF_MONTH);
        sYear=startCalendar.get(Calendar.YEAR);

        Calendar endCalendar=GregorianCalendar.getInstance();
        endCalendar.setTimeInMillis(endT);
        eMonth=endCalendar.get(Calendar.MONTH)+1;
        eYear=endCalendar.get(Calendar.YEAR);

        diffMonth=eMonth-sMonth;
        diffYear=eYear-sYear;

        if(diffMonth==0 && diffYear==0){
            System.out.println("Same month same year=====> "+sMonth + "-" + sDay + "-"+ sYear);
        }else if(diffMonth!=0 && diffYear==0){
            for (int x = sMonth; x <= 12; x++) {
                System.out.println("Diff month same year =====> "+x + "-" + sDay + "-"+ sYear);
            }
        }else  { 
            int numberOfYear = Math.abs(sYear - eYear) ;
            Integer yearsArray[] = new Integer[numberOfYear+1];
            for (int i = 0; i <= numberOfYear; i++) {
                yearsArray[i] = sYear + i;
            }
            for (int j = 0; j < yearsArray.length ; j++) {
             if (j == 0) {
                    for (int x = sMonth; x <= 12; x++) {
                        System.out.println("Diff month Diff year 1=====> "+ x+ "-" + sDay + "-"+ sYear);
                    }
                } else if (j < yearsArray.length-1) {
                    for (int x = 1; x <= 12; x++) {
                        System.out.println("Diff month Diff year 2=====> "+x + "-" + sDay + "-" + yearsArray[j]);
                    }
                } else {
                    for (int x = 1; x <= eMonth; x++) {
                        System.out.println("Diff month Diff year 3=====> "+x + "-" + sDay + "-" + yearsArray[j]);
                    }
                }
            }
        }
    }

    private void computeYearly(long starT,long endT){
        int sMonth;
        int sYear;
        int sDay;

        int eMonth;
        int eYear;
        int eDay;

        int diffMonth;
        int diffYear;

        Calendar startCalendar=GregorianCalendar.getInstance();
        startCalendar.setTimeInMillis(starT);
        sMonth=startCalendar.get(Calendar.MONTH)+1;
        sDay=startCalendar.get(Calendar.DAY_OF_MONTH);
        sYear=startCalendar.get(Calendar.YEAR);

        Calendar endCalendar=GregorianCalendar.getInstance();
        endCalendar.setTimeInMillis(endT);
        eMonth=endCalendar.get(Calendar.MONTH)+1;
        eDay=endCalendar.get(Calendar.DAY_OF_MONTH);
        eYear=endCalendar.get(Calendar.YEAR);

        diffMonth=eMonth-sMonth;
        diffYear=eYear-sYear;

        if(diffMonth==0 && diffYear==0){
            System.out.println("Same month same year=====> "+sMonth + "-" + sDay + "-"+ sYear);
        }else if(diffMonth!=0 && diffYear==0){
            System.out.println("diff month same year=====> "+sMonth + "-" + sDay + "-"+ sYear);
        }else  { 
            int numberOfYear = Math.abs(sYear - eYear) ;
            Integer yearsArray[] = new Integer[numberOfYear+1];
            for (int i = 0; i <= numberOfYear; i++) {
                yearsArray[i] = sYear + i;
            }
            for (int j = 0; j < yearsArray.length ; j++) {
                if (j == 0) {
                    System.out.println("diff month diff year=====> "+sMonth + "-" + sDay + "-"+ sYear);
                } else if (j < yearsArray.length-1) {
                    System.out.println("diff month diff year=====> "+sMonth + "-" + sDay + "-"+ yearsArray[j]);
                } else {
                    System.out.println("diff month diff year=====> "+sMonth + "-" + eDay + "-"+  yearsArray[j]);
                }
            }
        }
    }

    private int getNumberOfDaysInMonth(int currentMonth,boolean isLeapYear){
        int days = 0;

        if (currentMonth==1){
            days=31;
        }else if(currentMonth==2){
            if(isLeapYear)
                days=29;
            else
                days=28;
        }else if(currentMonth==3){
            days=31;
        }else if(currentMonth==4){
            days=30;    
        }else if(currentMonth==5){
            days=31;
        }else if(currentMonth==6){
            days=30;
        }else if(currentMonth==7){
            days=31;
        }else if(currentMonth==8){
            days=31;
        }else if(currentMonth==9){
            days=30;
        }else if(currentMonth==10){
            days=31;
        }else if(currentMonth==11){
            days=30;
        }else if(currentMonth==12){
            days=31;
        }
        return days;
    }
}
0
Basil Bourque On

If you mean something like saying a little girl is:

6 years, 4 months, and 3 days old

…a description of a span of time?

Then you need the Period, PeriodFormatter, and PeriodFormatterBuilder classes in Joda-Time 2.3.

See the question, Joda-Time: what's the difference between Period, Interval and Duration?

See this discussion on Period in Joda-Time doc.

From the doc in Joda-Time…

For example, a formatter that prints years and months, like "15 years and 8 months", can be constructed as follows:

PeriodFormatter yearsAndMonths = new PeriodFormatterBuilder()
 .printZeroAlways()
 .appendYears()
 .appendSuffix(" year", " years")
 .appendSeparator(" and ")
 .printZeroRarelyLast()
 .appendMonths()
 .appendSuffix(" month", " months")
 .toFormatter();
0
Techfist On

if you have date in millis, then below provided java class is your answere to get all you need.

http://docs.oracle.com/javase/7/docs/api/java/util/Calendar.html

also, if you have two date ranges then, all you can do simply is, calculate difference in millis, divide them to calculate seconds, then hours , days and month and so on to get all of your need.

0
Apoorv On

You can use

public String getElapsedDaysText(Calendar c1, Calendar c2)
{
    String elapsedDaysText = null;
    try
    {
        long milliSeconds1 = c1.getTimeInMillis();
        long milliSeconds2 = c2.getTimeInMillis();
        long periodSeconds = (milliSeconds2 - milliSeconds1) / 1000;
        long elapsedDays = periodSeconds / 60 / 60 / 24;
        elapsedDaysText = String.format("%d days", elapsedDays);
    }
    catch (Exception e)
    {
        Logger.LogError(e);
    }
    return elapsedDaysText;
}

where c1 is the present date and c2 is some date in the future. If you want to calculate past date c2 is past date and c1 is present date.

You can use the same method to find weeks,months and year by making some changes.

0
keshav On

I think you can use this (java.util.Date)

Date date=new Date(millis);
0
Sagar Maiyad On
Calendar c1, c2;


long ms1= c1.getTimeInMillis();
long ms2= c2.getTimeInMillis();
long totalsec = (ms2- ms1) / 1000;

int days = (int) ((totalsec/ (1000*60*60*24)) % 7);
int weeks = (int) (totalsec/ (1000*60*60*24*7));
int months = weeks/30;
int years = months/365;
0
Jackie On

CalDroid might solve your problem. You can find its source code and Example here.

public static long getDayDiff(long startDay, long endDay) {
long diff = endDay - startDay;
long diffDays = diff / (24 * 60 * 60 * 1000);
return diffDays;
}

so diffWeek = diffDays/7; and then for month, year.

0
Jorgesys On

Find number of days, weeks, months and year between two milliseconds.

This is a method using Date, Calendar and TimeUnit classes:

private String getAge(long start, long end){

    long milliseconds = TimeUnit.MILLISECONDS.toMillis(Math.abs(end - start));

    Calendar c = Calendar.getInstance();
    c.setTimeInMillis(milliseconds);
    int mYear = c.get(Calendar.YEAR)-1970;
    int mMonth = c.get(Calendar.MONTH);
    int mDay = c.get(Calendar.DAY_OF_MONTH)-1;
    int mWeek = (c.get(Calendar.DAY_OF_MONTH)-1)/7; 

    return "The difference is " + mYear + " years, " + mMonth + " months, " + mDay + " days. " + mWeek + " Weeks.";
}

this is an example calling the function:

System.out.println(getAge2(1538110800000L ,  479628000000L));

Output:

The difference is 33 years, 6 months, 16 days. 2 Weeks.