How to transform currentTimeMillis to a readable date format in java?

How to transform currentTimeMillis to a readable date format in java?

You can transform the result of System.currentTimeMillis() to a readable date format in Java by using the java.util.Date class along with SimpleDateFormat or by using the newer java.time API introduced in Java 8 and later. Here are examples using both approaches:

  • Using java.util.Date and SimpleDateFormat (Java 7 and earlier):
import java.text.SimpleDateFormat; import java.util.Date; public class MillisToDateExample { public static void main(String[] args) { long currentTimeMillis = System.currentTimeMillis(); // Create a Date object from currentTimeMillis Date date = new Date(currentTimeMillis); // Create a SimpleDateFormat to format the date SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); // Format the date as a readable string String formattedDate = sdf.format(date); System.out.println("Current Time (formatted): " + formattedDate); } } 
  • Using java.time.Instant and java.time.format.DateTimeFormatter (Java 8 and later):
import java.time.Instant; import java.time.ZoneId; import java.time.format.DateTimeFormatter; public class MillisToDateTimeExample { public static void main(String[] args) { long currentTimeMillis = System.currentTimeMillis(); // Create an Instant from currentTimeMillis Instant instant = Instant.ofEpochMilli(currentTimeMillis); // Create a DateTimeFormatter to format the instant DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss") .withZone(ZoneId.systemDefault()); // You can specify a different time zone if needed // Format the instant as a readable string String formattedDateTime = formatter.format(instant); System.out.println("Current Time (formatted): " + formattedDateTime); } } 

Both of these examples will format the current time obtained from System.currentTimeMillis() into a readable date and time format. You can customize the format pattern in the SimpleDateFormat or DateTimeFormatter to match your desired output format.


More Tags

jquery-ui google-query-language froala dylib drupal-modules abstract pyusb delphi-10.2-tokyo csproj jpda

More Java Questions

More Various Measurements Units Calculators

More Bio laboratory Calculators

More Chemical thermodynamics Calculators

More Trees & Forestry Calculators