如何以编程方式在android中获取从一个月开始到现在的经过时间

我想以编程方式在android中获取从一个月开始到现在的经过时间 .

最好使用Calendar.getInstance() .

例如今天是12/10/2018 . 因此,以毫秒为单位的持续时间为12/01/2018至12/10/2018

回答(3)

2 years ago

您可以使用 calendar.set(year,month,1,0,0,0); 获取该月第一天的时间戳 .

Calendar calendar = Calendar.getInstance();
Date d = new Date(1544371200000L); //12/10/2018
calendar.setTime(d);     
int year = calendar.get(Calendar.YEAR);
int month = calendar.get(Calendar.MONTH);
calendar.set(year,month,1,0,0,0);
Date firstDayOfMonth = calendar.getTime();
long duration = d.getTime() - firstDayOfMonth.getTime();

2 years ago

是你创建一个新日历并填充它的问题?您可以创建一个空的,只需填充您感兴趣的字段 .

Calendar now = Calendar.getInstance();

  Calendar startOfMonth = new GregorianCalendar();
    calendar.set(Calendar.DAY_OF_MONTH, 1); //first day of month
    calendar.set(Calendar.MONTH, now.get(Calendar.MONTH));
    calendar.set(Calendar.YEAR,  now.get(Calendar.YEAR);

  timeElapsed = now.getTimeInMillis() -  startOfMonth.getTimeInMillis() ;

2 years ago

要检索月初:

val cal = Calendar.getInstance()
cal.set(Calendar.HOUR_OF_DAY, 0)
cal.clear(Calendar.MINUTE)
cal.clear(Calendar.SECOND)
cal.clear(Calendar.MILLISECOND)
cal.set(Calendar.DAY_OF_MONTH, 1)

然后计算以毫秒为单位的经过时间:

val current = Calendar.getInstance()
val timePassedMilliseconds=current.timeInMillis-cal.timeInMillis