[英]how to get the elapsed time from the beginning of a month to now in android programmatically
I want to to get the elapsed time from the beginning of a month to now in android programmatically. 我想以编程方式在Android中获取从一个月初到现在的经过时间。
preferably using Calendar.getInstance(). 最好使用Calendar.getInstance()。
For example today is 12/10/2018. 例如今天是12/10/2018。 so the duration in millisecs will be 12/01/2018 to 12/10/2018
因此以毫秒为单位的持续时间将为12/01/2018至12/10/2018
To retrieve the beginning of the month: 要检索月初:
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)
Then to calculate elapsed in milliseconds: 然后计算经过的毫秒数:
val current = Calendar.getInstance()
val timePassedMilliseconds=current.timeInMillis-cal.timeInMillis
is your problem creating a new Calendar and populating it? 创建新日历并填充日历时出现问题吗? you can create an empty one, and just populate with the fields that you are interested in.
您可以创建一个空字段,然后只填充您感兴趣的字段。
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() ;
You can use calendar.set(year,month,1,0,0,0);
您可以使用
calendar.set(year,month,1,0,0,0);
to get the timestamp of the first day of the month. 以获得每月第一天的时间戳。
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();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.