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

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

Susan Sarandon
Susan SarandonOriginal
2024-11-01 07:14:30693browse

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>
  • 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>

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>
  • 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>

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!

Statement:
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