Java – Date and Time – Part 2

Date and time in Java

So we would just continue with Date and Time. You can review Date and Time Part 1 if you have not.


In this tutorial, we would cover the following

  1. Formatting Date Using print()
  2. Date and Time Conversion Codes
  3. Converting Dates to Strings
  4. Sleeping for Some Time
  5. How to Get Elapsed Time


1. Formatting Date Using printf()

Similar to the way you format string using printf, you can also format dates using printf. You can review Java Strings and Formatting.

Unlike formatting string, you use a two-letter format specifier to format dates. The first letter is t, then followed by a second letter indicating the format. So instead of %c, we have %tc. Instead of %d, we have %td. And so on.

For example, run the code in Listing 1.0 below.


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

public class DateDemo {

	public static void main(String[] args) {
			//Create a new date
			Date date = new Date();
			//Format the date using String.format
			String strDate = String.format("Today is %tc", date);
			//Print the date using printf()

Listing 1.0: Formating date using String.Fomat and printf


This code in Listing 1.0 uses %tc  where c represents ‘complete date and time’. You can replace the %tc with %tD or %tF  or %tr. All these gives the date in other formats. You can find the complete list of formats in the next section.


2. Date and Time Conversion Codes

I would recommend you spend some time with the table below.

Character Code Brief description Example
c Complete date and time Tue May 04 06:31:52 CDT 2019
F ISO 8601 date format 2018-02-09
D U.S. formatted date (month/day/year) 02/04/2018
T 24-hour time format 13:05:19
r 12-hour time format 05:05:19 am
R 24-hour time, no seconds 15:06
Y 4-digit year (with leading zeroes) 2015
y Last 2 digits of the year (with leading zeroes) 05
C First 2 digits of the year (with leading zeroes) 25
B Full month name December
b Abbreviated name of month Jul
m 2-digit month (with leading zeroes) 04
d 2-digit day (with leading zeroes) 01
e 2-digit day (without leading zeroes) 3
A Full name of weekday Wednesday
a Abbreviated name of weekday Fri
j 3-digit day of year (with leading zeroes) 057
H 2-digit hour (with leading zeroes), between 00 and 23 11
k 2-digit hour (without leading zeroes), between 0 and 23 19
I 2-digit hour (with leading zeroes), between 01 and 12 04
l 2-digit hour (without leading zeroes), between 1 and 12 8
M 2-digit minutes (with leading zeroes) 03
S 2-digit seconds (with leading zeroes) 18
L 3-digit milliseconds (with leading zeroes) 038
N 9-digit nanoseconds (with leading zeroes) 038000000
P Uppercase morning or afternoon marker AM
p Lowercase morning or afternoon marker am
z RFC 822 numeric offset from GMT -0600
Z Time zone PST
s Seconds since 1970-01-01 00:00:00 GMT 2078861332
Q Milliseconds since 1970-01-01 00:00:00 GMT 20788613328374

Table 1.0: Date and Time Conversion Codes



3. Converting Strings to Dates

You can convert dates to string using the parsed() method. This method is provided by the SimpleDateFormat class. So the parse() method attempts to convert a string data to date data.

The code in Listing 1.1 demonstrates this.


import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Scanner;

public class DateDemo {

	public static void main(String[] args) {
		//Create a new SimpleDateFormat
		SimpleDateFormat ft = new SimpleDateFormat("yyyy-MM-dd");
		//Get a new date from input
		Scanner scanner = new Scanner(;
		System.out.print("Please enter a date: ");
		String strDate = scanner.nextLine();
		try {
			//Parse the string into a date
			Date dtDate = ft.parse(strDate);
			System.out.println("You entered " + dtDate);
		} catch (ParseException e) {
			System.out.println("Unable to convert to date" + ft);

Listing 1.1: Converting a String to a Data



4. Sleeping for some Time

You will be able to delay for a period of time. This time is specified in milliseconds. But to do this, you need to use a the sleep method from the Thread class

For example, the code below makes the program sleep for 2000 miliseconds (2 seconds)


import java.util.Date;

public class DateSleepDemo {
	public static void main(String args[]) {
		try {
			//Print current date
			System.out.print(new Date() + "\n");
			//Sleep for 2 seconds
			//Print current date after the sleep
			System.out.print(new Date());
		} catch (InterruptedException e) {
			System.out.println("Error occured: ");

Listing 1.2: Sleeping for a time


If you run the code above, you will have this result:

Sat Jan 19 13:20:19 CET 2019
Sat Jan 19 13:20:22 CET 2019

Note the the sleep code is surrounded by a try/catch block. This is because its possible for error to occur when working with threads


5. How to get Elapsed Time

Although the above code gives use the elapsed time, there is method used to get the real milliseconds that actually elapsed.

This method is currentTimeMIllis. So instead of using new Date(), we use System.currentTimeMillis().

The code below illustrates this.


import java.util.Date;

public class ElapsedTimeDemo {

	public static void main(String[] args) {
		long begin = System.currentTimeMillis();
		System.out.println(new Date() + "\n");
		try {
			System.out.println(new Date() + "\n");
			long end = System.currentTimeMillis();
			long elapsed = end - begin;
			System.out.println("Elapsed time is " + elapsed);
		} catch (InterruptedException e) {
			System.out.println("Error occured: ");


Listing 1.3: Measuring elapsed time.


If you run the code in Listing 1.3 above, you will get the output:


Sat Jan 19 13:39:53 CET 2019

Sat Jan 19 13:39:58 CET 2019

Elapsed time is 5028