我正在尝试将毫秒日期转换为years months weeks和的数量days.
例如:5 months, 2 weeks and 3 days或1 year and 1 day.
我不想要:7 days或者4 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);
Run Code Online (Sandbox Code Playgroud)
我必须在天数上加1,因为如果我有23个小时应该是1天.
请解释如何正确转换它,我认为有更有效的方法来做到这一点.
Sho*_*uri 29
我总是使用它从毫秒开始等几年,反之亦然.直到现在我没有遇到任何问题.希望能帮助到你.
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);
Run Code Online (Sandbox Code Playgroud)
感谢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
Run Code Online (Sandbox Code Playgroud)
再次感谢你!