Home Tutorial Java Corejava Javatext Formatting the Time Using a Custom Format

 
 

Formatting the Time Using a Custom Format
Posted on: October 12, 2010 at 12:00 AM
Advertisement
In this section, you will learn how to format the time using a custom format.

Formatting the Time Using a Custom Format

In this section, you will learn how to format the time using a custom format.

Formatting and parsing is now become a simple task. We have so many classes to format different objects like data, time, message etc. Here we are going to format the time using a custom format. For this task, the class SimpleDateFormat is more approriate. It uses unquoted letters from 'A' to 'Z' and from 'a' to 'z' and interpret them as pattern letters for  representing the components of a date or time string. For example,
h:
It denotes the hour in am/pm.
m: It denotes minute in hour.
s: It denotes the second in minute.
a: It denotes the am/pm marker.

In the given example, we have created an instance of SimpleDateFormat class and specify the pattern for default locale. Then we have invoked the format() method which includes the date object. This method formats the time in the given pattern.

Here is the code:

import java.text.*;
import java.util.*;

public class FormattingTime {
	public static void main(String[] args) {
		SimpleDateFormat sdf = new SimpleDateFormat("hh:mm:ss a");
		String dateString = sdf.format(new Date());
		System.out.println(dateString);
	}
}

Output:

11:07:37 AM
Advertisement

Related Tags for Formatting the Time Using a Custom Format:


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: October 12, 2010

Recommend the tutorial

Advertisements Advertisements
 

 

 

DMCA.com