April 25, 2026
Date and time in Java

Java – Date and Time – Part 2

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()
			System.out.printf(strDate);					
	}
}

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 CodeBrief descriptionExample
cComplete date and timeTue May 04 06:31:52 CDT 2019
FISO 8601 date format2018-02-09
DU.S. formatted date (month/day/year)02/04/2018
T24-hour time format13:05:19
r12-hour time format05:05:19 am
R24-hour time, no seconds15:06
Y4-digit year (with leading zeroes)2015
yLast 2 digits of the year (with leading zeroes)05
CFirst 2 digits of the year (with leading zeroes)25
BFull month nameDecember
bAbbreviated name of monthJul
m2-digit month (with leading zeroes)04
d2-digit day (with leading zeroes)01
e2-digit day (without leading zeroes)3
AFull name of weekdayWednesday
aAbbreviated name of weekdayFri
j3-digit day of year (with leading zeroes)057
H2-digit hour (with leading zeroes), between 00 and 2311
k2-digit hour (without leading zeroes), between 0 and 2319
I2-digit hour (with leading zeroes), between 01 and 1204
l2-digit hour (without leading zeroes), between 1 and 128
M2-digit minutes (with leading zeroes)03
S2-digit seconds (with leading zeroes)18
L3-digit milliseconds (with leading zeroes)038
N9-digit nanoseconds (with leading zeroes)038000000
PUppercase morning or afternoon markerAM
pLowercase morning or afternoon markeram
zRFC 822 numeric offset from GMT-0600
ZTime zonePST
sSeconds since 1970-01-01 00:00:00 GMT2078861332
QMilliseconds since 1970-01-01 00:00:00 GMT20788613328374

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.in);
		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);
			e.printStackTrace();
		}				
	}
}

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
			Thread.sleep(2000);			
			
			//Print current date after the sleep
			System.out.print(new Date());
			
		} catch (InterruptedException e) {
			System.out.println("Error occured: ");
			e.printStackTrace();
		}		
	}
}

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 {
			Thread.sleep(5000);
			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: ");
			e.printStackTrace();
		}
		
		
	}

}

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
3 1 vote
Article Rating
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x