- 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
Advertisements