How to Get Current System Time in Java

Get Current System Time in Java

In this example, We will show you simple program about, How to get current system time in Java, both (12-hour time) and (24-hour time). The sample program has been tested with environment and output shared in the same post.

How to Get Current System Time in Java

#1 Getting Current System Time in (12-hour time)

package com.dineshkrish;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 
 * @author Dinesh Krishnan
 *
 */

public class CurrentTime {

	public static void main(String[] args) {
		
		// creating date object
		Date date = new Date();
		
		// time format
		String format = "hh:mm:ss a";
		
		// creating format object
		DateFormat df = new SimpleDateFormat(format);
		
		// formatting the date
		String time = df.format(date);
		
		// printing the result
		System.out.println("The current system time is : "+time);
		
	}
}

Output

The current system time is : 02:24:02 PM

#2 Getting Current System Time in (24-hour time)

package com.dineshkrish;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 
 * @author Dinesh Krishnan
 *
 */

public class CurrentTime {

	public static void main(String[] args) {
		
		// creating date object
		Date date = new Date();
		
		// time format (24 hrs)
		String format = "HH:mm:ss a";
		
		// creating format object
		DateFormat df = new SimpleDateFormat(format);
		
		// formatting the date
		String time = df.format(date);
		
		// printing the result
		System.out.println("The current system time is : "+time);
		
	}
}

Output

The current system time is : 14:25:08 PM

References

1. Java SimpleDateFormat Class
2. Java DateFormat Class
3. Java Date Class