- 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 date with SimpleDateFormat
The SimpleDateFormat class is used to parse and format dates. To create an object, firstly import the following package
import java.text.SimpleDateFormat;
Set the date
String strDate = "'Year = '"; strDate += "yyyy"; strDate += "'
Month = '"; strDate += "MMMMMMMMM"; strDate += "'
Hours = '"; strDate += "hh"; strDate += "a"; strDate += "'
Minutes = '"; strDate += "mm"; strDate += "'
Seconds = '"; strDate += "ss";
Now, create an object and format the date −
SimpleDateFormat dateFormat = new SimpleDateFormat(strDate); String formattedDate = dateFormat.format(new Date());
The following is an example −
Example
import java.text.SimpleDateFormat; import java.util.Date; public class Demo { public static void main(String args[]) { String strDate = "'Year = '"; strDate += "yyyy"; strDate += "'
Month = '"; strDate += "MMMMMMMMM"; strDate += "'
Hours = '"; strDate += "hh"; strDate += "a"; strDate += "'
Minutes = '"; strDate += "mm"; strDate += "'
Seconds = '"; strDate += "ss"; System.out.println("Date and Time...."); SimpleDateFormat dateFormat = new SimpleDateFormat(strDate); String formattedDate = dateFormat.format(new Date()); System.out.println(formattedDate); } }
Output
Date and Time.... Year = 2018 Month = November Hours = 09AM Minutes = 12 Seconds = 41
Advertisements