【问题标题】:Best way to convert Milliseconds to number of years, months and days [duplicate]将毫秒转换为年数、月数和天数的最佳方法 [重复]
【发布时间】:2013-03-05 20:27:53
【问题描述】:

我正在尝试将毫秒日期转换为 years months weeksdays 的数量。

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

我不想要:7 days4 weeks > 这应该是 1 week1 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 天。

请说明如何正确转换,我认为有更有效的方法。

【问题讨论】:

  • 使用CalendarsetTimeInMillis()
  • 你能举个例子吗?我没有正确理解你..
  • 好的,我在日历对象中设置了日期。我现在该怎么办?我想知道多少天,几周等。在里面,而不是日期本身。

标签: java android date


【解决方案1】:

来源:Convert time interval given in seconds into more human readable form

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

}

【讨论】:

  • 闰年呢?
【解决方案2】:

我总是使用它来获取毫秒数等年份,反之亦然。到目前为止,我没有遇到任何问题。希望对您有所帮助。

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

【讨论】:

  • 我想知道多少天、多少周等。在里面,而不是日期本身。
  • 毫秒是从 1970 年 1 月 1 日开始计算的。因此,您有最终日期和初始日期。使这种逻辑在两个日期之间获取天数、月数等应该不难。
  • 我认为它有效。 int mYear = c.get(Calendar.YEAR)-1970; int mMonth = c.get(Calendar.MONTH); int mDay = c.get(Calendar.DAY_OF_MONTH)-1; 请告诉我这是否正确。
  • 看起来不错。我想他们应该不需要从当前天数中减去 1 天,因为 1970 年 1 月 1 日也以毫秒为单位。
  • 是的,但是如果我的毫秒时间是 86400000(= 1 天),我会得到 2 days。你知道为什么吗?
【解决方案3】:

感谢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

再次感谢您!

【讨论】:

  • 日历 c = Calendar.getInstance(); //以毫秒为单位设置时间 c.setTimeInMillis(milliseconds); int mYear = c.get(Calendar.YEAR); int mMonth = c.get(Calendar.MONTH); int mDay = c.get(Calendar.DAY_OF_MONTH);
  • 你能解释一下它是如何工作的吗?它如何返回月数?
猜你喜欢
  • 2013-11-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-05-20
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多