Home >Java >javaTutorial >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:
<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>
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>
<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!