Polar
Polar

Reputation: 3537

Set Calendar Date to Current Date

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?

Upvotes: 0

Views: 1597

Answers (2)

Andreas
Andreas

Reputation: 159096

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);

Upvotes: 1

Blundell
Blundell

Reputation: 76466

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);

Upvotes: 3

Related Questions