How to set 24-hours format for date on java?

How to set 24-hours format for date on java?

In Java, you can format a date in a 24-hour format using the SimpleDateFormat class or the DateTimeFormatter class, depending on your version of Java. Here are examples of both approaches:

  1. Using SimpleDateFormat (Java 7, 8, and earlier):

    import java.text.SimpleDateFormat; import java.util.Date; public class DateFormatExample { public static void main(String[] args) { Date date = new Date(); // Create a Date object with the current date and time SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss"); // Create a SimpleDateFormat with the desired format String formattedDate = sdf.format(date); // Format the date System.out.println("Formatted Date (24-hour format): " + formattedDate); } } 

    In this example, "HH:mm:ss" specifies a 24-hour format for the time portion.

  2. Using DateTimeFormatter (Java 8 and later):

    import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; public class DateFormatExample { public static void main(String[] args) { LocalDateTime dateTime = LocalDateTime.now(); // Create a LocalDateTime object with the current date and time DateTimeFormatter formatter = DateTimeFormatter.ofPattern("HH:mm:ss"); // Create a DateTimeFormatter with the desired format String formattedDateTime = dateTime.format(formatter); // Format the date and time System.out.println("Formatted Date (24-hour format): " + formattedDateTime); } } 

    In this example, "HH:mm:ss" specifies a 24-hour format for the time portion.

Both of these approaches allow you to format the date in a 24-hour format. You can customize the format pattern as needed to include additional date and time components if required.


More Tags

fscalendar greatest-n-per-group nose python-idle android-arrayadapter tcp-keepalive jsse any android-listfragment chatterbot

More Java Questions

More Various Measurements Units Calculators

More Geometry Calculators

More Cat Calculators

More Stoichiometry Calculators