- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Java Program to format time using Custom Format
Firstly, set the time with SimpleDateFormat class
Format dateFormat = new SimpleDateFormat("h:m:s");
Now, for custom format, let us fetch the hour, minute and second individually
Hour
// hour dateFormat = new SimpleDateFormat("h"); String strHour = dateFormat.format(new Date()); System.out.println("Hour: "+strHour);
Minute
// minute dateFormat = new SimpleDateFormat("m"); String strMinute = dateFormat.format(new Date()); System.out.println("Minute: "+strMinute);
Second
// second dateFormat = new SimpleDateFormat("s"); String strSecond = dateFormat.format(new Date()); System.out.println("Second: "+strSecond);
The following is an example −
Example
import java.text.Format; import java.text.SimpleDateFormat; import java.util.Date; public class Demo { public static void main(String[] argv) throws Exception { Format dateFormat = new SimpleDateFormat("h:m:s"); String str = dateFormat.format(new Date()); System.out.println("Time: "+str); // hour dateFormat = new SimpleDateFormat("h"); String strHour = dateFormat.format(new Date()); System.out.println("Hour: "+strHour); // minute dateFormat = new SimpleDateFormat("m"); String strMinute = dateFormat.format(new Date()); System.out.println("Minute: "+strMinute); // second dateFormat = new SimpleDateFormat("s"); String strSecond = dateFormat.format(new Date()); System.out.println("Second: "+strSecond); } }
Output
Time: 10:58:52 Hour: 10 Minute: 58 Second: 52
- Related Articles
- Java Program to parse Time using custom format
- Java Program to Format time in AM-PM format
- Java Program to format time with DateFormat.MEDIUM
- Java Program to format time with DateFormat.LONG
- Java Program to format date time with Join
- Java Program to display Time in 12-hour format
- Java Program to display time in 24-hour format
- Java Program to Display time in different country’s format
- How to format time using printf() method in Java?
- Java Program to format Month in MMMM format
- Java Program to format LocalDateTime as ISO_WEEK_DATE format
- Java Program to format LocalTimeDate as BASIC_ISO_DATE format
- Java Program to format hour in H (0-23) format in Java
- Format time with DateFormat.SHORT in Java
- Format time with DateFormat.FULL in Java

Advertisements