Home > Java > javaTutorial > How to Convert currentTimeMillis to a Date with Locale-Specific Formatting?

How to Convert currentTimeMillis to a Date with Locale-Specific Formatting?

Susan Sarandon
Release: 2024-11-01 07:14:30
Original
829 people have browsed it

How to Convert currentTimeMillis to a Date with Locale-Specific Formatting?

How to Convert currentTimeMillis to a Date with Locale-Specific Formatting

Problem:

When converting milliseconds to a date format using SimpleDateFormat, the program uses the date of the machine, which may not represent the correct time in a different time zone.

Solution:

To handle this issue elegantly, you can use the following approaches:

  • Java.util.Date:
<code class="java">Date date = new Date(millis);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss,SSS", Locale.US);
String formattedDate = sdf.format(date);</code>
Copy after login
  • Java Time API (Java 8 ):

Using Instant and ZonedDateTime:

<code class="java">Instant instant = Instant.ofEpochMilli(millis);
ZonedDateTime zonedDateTime = ZonedDateTime.ofInstant(instant, ZoneId.of("US/Central"));

// Format the date
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss,SSS");
String formattedDate = zonedDateTime.format(formatter);</code>
Copy after login

Using LocalDateTime:

<code class="java">LocalDateTime localDateTime = LocalDateTime.ofInstant(instant, ZoneId.of("US/Central"));

// Format the date
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss,SSS");
String formattedDate = localDateTime.format(formatter);</code>
Copy after login
  • Joda-Time (legacy)
<code class="java">DateTime jodaTime = new DateTime(millis, DateTimeZone.forTimeZone(TimeZone.getTimeZone("US/Central")));

// Format the date
DateTimeFormatter parser1 = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss,SSS");
String formattedDate = parser1.print(jodaTime);</code>
Copy after login

By using these approaches, you can convert milliseconds to a date format in a locale-specific manner, ensuring that the correct time is represented.

The above is the detailed content of How to Convert currentTimeMillis to a Date with Locale-Specific Formatting?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template