0

I have variable with value of timeInMills which is past 3 days ago, I wanted to reset the date of it to current date but the time should be still.

Calendar calNow = Calendar.getInstance();
Calendar calSets = (Calendar)calNow.clone();

calSets.setTimeInMillis(TIME_IN_MILL); //set datetime from timeInMillis
//Reset the date to current Date.

How to do that?

Polar
  • 3,327
  • 4
  • 42
  • 77

2 Answers2

3

Like this, get the properties you want, before you change the instance:

Calendar calNow = Calendar.getInstance();
Calendar calSets = (Calendar)calNow.clone();

int hours = calNow.get(Calendar.HOUR_OF_DAY)
int minutes = calNow.get(Calendar.MINUTE)

calSets.setTimeInMillis(TIME_IN_MILL); //set datetime from timeInMillis
//Reset the date to current Date.

calSets.set(Calendar.SECOND, 0);
calSets.set(Calendar.MILLISECOND, 0);
calSets.set(Calendar.HOUR_OF_DAY, hours);
calSets.set(Calendar.MINUTE, minutes);
Blundell
  • 75,855
  • 30
  • 208
  • 233
  • I need the hours and minutes from TIME_IN_MILL not from the Current Time, is that correct? – Polar Jul 18 '19 at 15:52
  • I have made some changes from my question please see it. – Polar Jul 18 '19 at 15:59
  • do the same thing, I have shown. Except take the date (day, month, year) off the current time now (instead of the hours and minutes) and set it on the `calSets` time – Blundell Jul 18 '19 at 16:04
  • No need for 2 Calendar objects. Isn't that the point of the "before you change the instance" part of the answer? – Andreas Jul 18 '19 at 16:25
1

You can reset a Calendar by calling 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()));

The code prints 2019-07-18 15:30:00.000, which is todays date with the time of day from the TIME_IN_MILL value.

If you don't want to rely on System.currentTimeMillis(), just get the value from the Calendar object, first thing:

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);
Andreas
  • 154,647
  • 11
  • 152
  • 247