Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 ? :-(

like image 748
Akhilesh Mani Avatar asked Feb 02 '26 07:02

Akhilesh Mani


1 Answers

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.

like image 57
Apoorv Avatar answered Feb 04 '26 22:02

Apoorv