以毫秒转换为年,月,天数的最佳方法 [英] Best way to convert Milliseconds to number of years, months and days

查看:267
本文介绍了以毫秒转换为年,月,天数的最佳方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图毫秒日期转换的 周数

例如:5个月,2周和3天 1年零1天

我不希望: 7天4周>这应该是 1周1个月

我试过一些方法,但它始终成为像 7天,0周

我的code:

  INT周=(INT)Math.abs(timeInMillis /(24 * 60 * 60 * 1000 * 7));
INT天数=(INT)timeInMillis /(24 * 60 * 60 * 1000)+1);

我要加1天数,因为如果我有23个分,这应该是1天。

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


解决方案

我总是用这从毫秒获得年等,反之亦然。到现在我已经与它没有任何问题。希望它帮助。

 进口java.util.Calendar中;日历C = Calendar.getInstance();
//以毫秒为单位设置时间
c.setTimeInMillis(毫秒);
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分钟= c.get(Calendar.MINUTE);
INT秒= c.get(Calendar.SECOND);

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.

解决方案

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

这篇关于以毫秒转换为年,月,天数的最佳方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆