1

I want to increment an hour to the current time and also get the date in UTC. I tried to use Calender class but that only increments the hour but doesn't give the Date in UTC timezone, on the other hand, SimpleDateFormat sets the timezone but doesn't increment an hour. How to do it?

public static void main(String[] args) 
{
  Date currentDate = new Date();

  Calendar calendar = Calendar.getInstance();
  calendar.add(Calendar.HOUR, 1);
  calendar.setTimeZone(TimeZone.getTimeZone("UTC"));

  SimpleDateFormat simpleDateFormat = new SimpleDateFormat("EEE MMM d HH:mm:ss z yyyy");
  simpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
  simpleDateFormat.format(calendar.get(Calendar.HOUR));

  String dateOfDeletion = simpleDateFormat.format(new Date()).toString();
  System.out.println(currentDate) ;
  System.out.println(dateOfDeletion);
  System.out.print(calendar.getTime());
}

Output:

Mon Jun 26 14:05:56 IST 2023
Mon Jun 26 08:35:56 UTC 2023
Mon Jun 26 15:05:56 IST 2023

I want the date to be in UTC with 1 hour incremented from the current time.

tquadrat
  • 3,033
  • 1
  • 16
  • 29
  • You forgot to format the result of `calendar.getTime()` with the `SimpleDateFormat`. Change your last line to: `System.out.println(simpleDateFormat.format(calendar.getTime()));`. Better: Do not use the old `java.util.Date` and `java.util.Calendar` classes anymore; use the classes from the package `java.time`. – Jesper Jun 26 '23 at 09:05
  • I strongly recommend that you don’t use `Date`, `Calendar` and `SimpleDateFormat`. All of those classes were poorly designed, the last in particular notoriously troublesome, and all are long outdated. Use `Instant` and/or other classes from [java.time, the modern Java date and time API](https://docs.oracle.com/javase/tutorial/datetime/index.html). If you indispensbly need a `Date` for an API that you cannot afford to upgrade just now, use `Date.from(Instant.now().plus(Duration.ofHours(1)))`. The `Date` will always print in the local time zone of your JVM, though, nothing we can do about that. – Ole V.V. Aug 05 '23 at 14:12

1 Answers1

2

Try ZonedTimeDate:

final var dateOfDeletion = ZonedDateTime.now()
  .plusHours( 1 )
  .withZoneSameInstant( ZoneId.of( "UTC" ) );

now() gives you the current time, plusHours() moves that by the given number of hours, and withZoneSameInstant() changes the time zone, by keeping the time (the instant).

Originally, I used withZoneSameLocal(), but that just replaces the original time zone with the given one, without adjusting the time (the instant); in most cases this is not what you want.

If you really need an instance of java.util.Date you can convert dateOfDeletion, but that means you will lose the time zone again.

If you just need the date as a string, dateOfDeletion.toString() already does the job for an ISO 8601 format. Other formats are possible through a DateTimeFormatter instance.

Refer to the documentation of the java.time package.


From the comments, I understood that the PO just want to have a java.util.Date adjusted by one hour, provided in UTC.

Internally, an instance of java.util.Date is just a thin wrapper around a long representing the milliseconds since the begin of the epoch (1970-01-01T00:00:00.000 UTC). So Date::getTime returns this time, already for UTC. To get the adjusted Date instance, try this:

final var dateOfDeletion = new Date( new Date().getTime() + 3_600_000 );

But printing a Date instance with a time zone other than the default one is a challenge …

You can convert it to a Calendar instance and print that:

final var calendar = Calendar.getInstance( TimeZone.getTimeZone( "UTC" ) );
calendar.setTime( dateOfDeletion );
System.out.printf("%tDT%<tT %<tZ%n", calendar );

But still your Date has no time zone …

tquadrat
  • 3,033
  • 1
  • 16
  • 29
  • 1
    @NiharikaBaruah - please be aware that using `withZoneSameLocal` will return the local time plus one hour (with UTC), instead of the actual UTC time plus one hour. As example for 16:00 local time (10:30 UTC), it will return `17:00 UTC`, which is 6:30 hours in advance. You can use `withZoneSameInstant` to get the next hour in UTC ( e.g. `11:30 UTC` for above example, that is actual time 16:00 (10:30 UTC) - Not sure what the requirements are – user16320675 Jun 26 '23 at 10:45
  • @tquadrat Thanks using ZonedTimeDate worked. But I am getting the value as a string, I need the final result in Date format for an API implementation. But if I do "Date date =new Date(dateOfDeletion)" it loses the changes made by ZonedTimeDate. How to convert this "dateOfDeletion" into date format? – Niharika Baruah Jun 26 '23 at 13:00
  • 1
    @NiharikaBaruah – As said: `java.util.Date` does not have a timezone component. Instead it uses internally the milliseconds since the begin of the epoch, and when converted to a string, it uses the current timezone – no matter of useful or not. – tquadrat Jun 26 '23 at 14:13