• Register
0 votes
919 views

Problem :

I want to convert the Milliseconds in the format of number of years months weeks and days.

e.g. 10 months, 4 weeks and 5 days

I have already tried in few ways but it is becoming as 7 days and 0 weeks.

Please find below my code for your referance:

int weeks = (int) Math.abs(timeInMillis / (24 * 60 * 60 * 1000 * 7));

int days = (int) timeInMillis / (24 * 60 * 60 * 1000)+1);

I am trying the logic by adding 1 to number of days as if I have 23 hours it should be 1 day.

Please give me the solution on it.

7.5k points

Please log in or register to answer this question.

2 Answers

0 votes

Solution :

I had also faced this problem in the past. I had done lot of research on it and found the solution.

Please follow the below approach to resolve your issue.

I tend to use following code to get the years and other dates from the milliseconds and vice versa. Till now my below logic never failed . So I hope it helps to you too.

import java.util.Calendar;
long myday = (1000 * 60 * 60 * 24); //converting 24 hours in milliseconds
long mytime = myday * 40; //e.g. 40 days
Calendar mycal = Calendar.getInstance();
mycal.setTimeInMillis(time);
int myYear = mycal.get(Calendar.YEAR)-1970;
int myMonth = mycal.get(Calendar.MONTH); 
int myDay = mycal.get(Calendar.DAY_OF_MONTH)-1)%7;
int myWeek = (mycal.get(Calendar.DAY_OF_MONTH)-1)/7;
38.6k points
0 votes

Sometimes it is mandatory to reveal time in milliseconds as another alternative for time function. There is a good equation by which you can convert your time into milliseconds. The year may normal or leap year we assume normal year for this article and we will make an equation or formula to insert our system for time calculation in milliseconds.

Reason:  

In many websites and other systems which require time function we usually use second unit but it is more accurate and easy to use milliseconds instead of second. Basically it is used in many computer languages for more readability and functional of the time constraints.

Let’s use days, hours, minutes, seconds, and miliseconds

Now if a normal year has 365 days and,
1 day has 24 hours

1 hour has 60 minutes

1 minute has 60 seconds and

1 second has 1000 milliseconds

Then the number of milliseconds in a year can be calculated in this way;

Days multiply by hours multiply by minutes multiply by seconds multiply by milliseconds will give you the number of milliseconds in a year.

365 days x 24 hours x 60 minutes x 60 seconds x 1000 milliseconds

365x24x60x60x1000=31,536,000,000

This is a big number of billions milliseconds.

Solution:

So it becomes a good technique to calculate total milliseconds of a year in very short by using simple math calculation and formula. 

31.7k points