我有一个变量timeInMills
,它是3天前的值,我想将其日期重置为当前日期,但是时间应该仍然是。
Calendar calNow = Calendar.getInstance();
Calendar calSets = (Calendar)calNow.clone();
calSets.setTimeInMillis(TIME_IN_MILL); //set datetime from timeInMillis
//Reset the date to current Date.
该怎么做?
答案 0 :(得分:3)
像这样,在更改实例之前获取所需的属性:
i
答案 1 :(得分:1)
您可以通过调用Calendar
来重置setTimeInMillis(System.currentTimeMillis())
:
TimeZone.setDefault(TimeZone.getTimeZone("UTC")); // Just for testing
final long TIME_IN_MILL = 1563204600000L; // 2019-07-15 15:30 UTC
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(TIME_IN_MILL);
int hour = cal.get(Calendar.HOUR_OF_DAY);
int minute = cal.get(Calendar.MINUTE);
cal.setTimeInMillis(System.currentTimeMillis()); // Reset
cal.set(Calendar.HOUR_OF_DAY, hour);
cal.set(Calendar.MINUTE, minute);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
System.out.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").format(cal.getTime()));
代码显示2019-07-18 15:30:00.000
,它是从TIME_IN_MILL
值开始的今天的日期和一天中的时间。
如果您不想依赖System.currentTimeMillis()
,只需从Calendar
对象获取值,
Calendar cal = Calendar.getInstance();
long now = cal.getTimeInMillis();
cal.setTimeInMillis(TIME_IN_MILL);
int hour = cal.get(Calendar.HOUR_OF_DAY);
int minute = cal.get(Calendar.MINUTE);
cal.setTimeInMillis(now);
cal.set(Calendar.HOUR_OF_DAY, hour);
cal.set(Calendar.MINUTE, minute);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);