
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Format and Parse Date in Java
To format a date in Java, firstly import the following package.
import java.text.DateFormat;
Now, create DateFormat object.
DateFormat shortFormat = DateFormat.getDateInstance(DateFormat.SHORT); DateFormat longFormat = DateFormat.getDateInstance(DateFormat.LONG);
Use the format() method to format the above dates.
System.out.println(shortFormat.format(new Date())); System.out.println(longFormat.format(new Date()));
To parse the dates, use the parse() method.
Example
import java.text.DateFormat; import java.text.ParseException; import java.util.Date; public class Demo { public static void main(String[] args) throws Exception { // format date DateFormat shortFormat = DateFormat.getDateInstance(DateFormat.SHORT); DateFormat longFormat = DateFormat.getDateInstance(DateFormat.LONG); System.out.println("Format Date..."); System.out.println(shortFormat.format(new Date())); System.out.println(longFormat.format(new Date())); // parse date System.out.println("Parse Date..."); Date d1 = shortFormat.parse("11/21/2018"); System.out.println(d1); } }
Output
Format Date... 11/22/18 November 22, 2018 Parse Date... Wed Nov 21 00:00:00 UTC 2018
Advertisements