0

This code

String.format("%1$tY%1$tm%1$td", new Date());

gives a YYYYmmdd format using the current system time but the time zone is the current system default as well. How to make this code gives UTC date?

I tried

String.format("%1$tY%1$tm%1$td", Date.from(LocalDateTime.now().atZone(ZoneId.of("UTC")).toInstant()));

but not working.

Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110
user1589188
  • 5,316
  • 17
  • 67
  • 130

2 Answers2

3

Use ZonedDateTime:

ZonedDateTime zonedDateTime = ZonedDateTime.now().withZoneSameInstant(ZoneId.of("UTC"));
System.out.println(String.format("%1$tY%1$tm%1$td", zonedDateTime));
xingbin
  • 27,410
  • 9
  • 53
  • 103
  • Thank you! I thought String.format has to take a Date object. – user1589188 Sep 11 '20 at 03:03
  • 1
    @user1589188 - I suggest you use `DateTimeFormatter` which is not only specialized for formatting date, time, and time-zone information but also many other features like defaulting the parts of date-time to some values, localizing etc. – Arvind Kumar Avinash Sep 11 '20 at 10:27
2

Since you need to display just year, month and day, the most appropriate class for this would be LocalDate. Also, I suggest you use DateTimeFormatter which is not only specialized for formatting date, time, and time-zone information but also many other features like defaulting the parts of date-time to some values, localizing etc.

import java.time.LocalDate;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;

public class Main {
    public static void main(String[] args) {
        // Today at UTC
        LocalDate date = LocalDate.now(ZoneOffset.UTC);

        // Define the formatter
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("uuuuMMdd");

        // Display LocalDate in its default format
        System.out.println(date);

        // Display LocalDate in the custom format
        System.out.println(date.format(formatter));
    }
}

Output:

2020-09-11
20200911

Note that java.util.Date does not represent a Date/Time object. It simply represents the no. of milliseconds from the epoch of 1970-01-01T00:00:00Z. It does not have any time-zone or zone-offset information. When you print it, Java prints the string obtained by combining the date and time based on the time-zone of your JVM with the time-zone of your JVM. Date and time API from java.util is mostly deprecated and error-prone. I suggest you stop using java.util.Date and switch to java.time API.

The java.time API has a rich set of classes for different purposes e.g. if you need the information about the date and time, you can use LocalDateTime and if you need the information about the date, time, and time-zone, you can use ZonedDateTime or OffsetDateTime. The following table shows an overview of date-time classes available in java.time package:

enter image description here

Learn more about the modern date-time API from Trail: Date Time.

Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110