Java converting date time to 24 hour format

Java converting date time to 24 hour format

To convert a date and time to a 24-hour format (also known as military time) in Java, you can use the SimpleDateFormat class to format a Date or LocalDateTime object. Here's an example of how to do this:

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

In this example:

  1. We create a SimpleDateFormat object and specify the desired format pattern "HH:mm:ss", where:

    • "HH" represents the hour in 24-hour format (00-23).
    • "mm" represents the minutes (00-59).
    • "ss" represents the seconds (00-59).
  2. We obtain the current date and time using the Date class (you can also use LocalDateTime or other date/time classes if preferred).

  3. We format the date and time using dateFormat.format(now), where now is the Date object representing the current date and time.

  4. The result is a string containing the current time in 24-hour format, which we print to the console.

You can replace now with any Date or LocalDateTime object to format a specific date and time in 24-hour format. Adjust the format pattern in SimpleDateFormat to include other components like milliseconds or time zones if needed.


More Tags

lint except superscript watermark date-range imap mono class-attributes types records

More Java Questions

More Statistics Calculators

More Fitness-Health Calculators

More Entertainment Anecdotes Calculators

More Animal pregnancy Calculators