将毫秒转换为年,月和日的最佳方法

我正在尝试将毫秒日期转换为数weeks和数daysyears days

例如: 5 months, 2 weeks and 3 days1 year and 1 day

我不想要: 7 days4 weeks >这应该是1 week 1 month

我尝试了几种方法,但它总是变成7 days and 0 weeks

我的代码:

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

我必须在天数上加1,因为如果我有23个小时它应该是1天。

请解释如何正确转换它,我认为有更有效的方法来做到这一点。

我总是使用它来从毫秒开始等几年,反之亦然。 直到现在我没有遇到任何问题。 希望能帮助到你。

 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); 

感谢Shobhit Puri,我的问题得到了解决。

此代码计算给定时间内的月数,天数等,以毫秒为单位。 我用它来计算两个日期之间的差异。

完整解决方案

 long day = (1000 * 60 * 60 * 24); // 24 hours in milliseconds long time = day * 39; // for example, 39 days Calendar c = Calendar.getInstance(); c.setTimeInMillis(time); 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; // ** if you use this, change the mDay to (c.get(Calendar.DAY_OF_MONTH)-1)%7 

再次感谢你!

来源: 将以秒为单位的时间间隔转换为更易读的forms

 function secondsToString(seconds) { var numyears = Math.floor(seconds / 31536000); var numdays = Math.floor((seconds % 31536000) / 86400); var numhours = Math.floor(((seconds % 31536000) % 86400) / 3600); var numminutes = Math.floor((((seconds % 31536000) % 86400) % 3600) / 60); var numseconds = (((seconds % 31536000) % 86400) % 3600) % 60; return numyears + " years " + numdays + " days " + numhours + " hours " + numminutes + " minutes " + numseconds + " seconds"; }