Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to convert Milliseconds to number of years, months and days [duplicate]

Tags:

java

date

android

I'm trying to convert a Milliseconds date to number of years months weeks and days.

For example: 5 months, 2 weeks and 3 days or 1 year and 1 day.

I don't want: 7 days or 4 weeks > this should be 1 week and 1 month.

I tried few ways but it always became something like 7 days and 0 weeks.

My code:

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

I have to add 1 to number of days because if I have 23 hours it should be 1 day.

Please explain how to convert it correctly, I think that there is more efficient ways to do it.

like image 828
Dennis Avatar asked Mar 17 '13 12:03

Dennis


People also ask

How to convert milliseconds to date in Excel?

Milliseconds to date converter helps you to find the date and time from a given total number of milliseconds . This total number of milliseconds is the elapsed milliseconds since timestamp or unix epoch counting from 1 January 1970. Just enter the milliseconds value and press the Convert to Date button to find the date.

How many milliseconds are in a day?

A millisecond is one thousandth of a second. A day is the approximate time it takes for the Earth to complete one rotation. It is defined as exactly 86,400 seconds. Milliseconds to Days Conversion Table.

How to find the elapsed milliseconds since timestamp in Excel?

This total number of milliseconds is the elapsed milliseconds since timestamp or unix epoch counting from 1 January 1970. Just enter the milliseconds value and press the Convert to Date button to find the date. You can also set the milliseconds value from Now button to the current timestamp milliseconds.


1 Answers

I always use this for getting years etc from milliseconds and vice versa. Till now I've had no problems with it. Hope it helps.

import java.util.Calendar;

Calendar c = Calendar.getInstance(); 
//Set time in milliseconds
c.setTimeInMillis(milliseconds);
int mYear = c.get(Calendar.YEAR);
int mMonth = c.get(Calendar.MONTH); 
int mDay = c.get(Calendar.DAY_OF_MONTH);
int hr = c.get(Calendar.HOUR);
int min = c.get(Calendar.MINUTE);
int sec = c.get(Calendar.SECOND);
like image 198
Shobhit Puri Avatar answered Nov 03 '22 03:11

Shobhit Puri