- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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
How to format a date to String in Java?
The java.text package provides a class named SimpleDateFormat which is used to format and parse dates in required manner (local).
Using the methods of this class you can parse String to Date or, format Date to String.
Formatting Date to String
You can format a given String to Date object using the parse() method of the SimpleDateFormat class. To this method you need to pass the Date in String format. To format a String to Date object −
Instantiate the SimpleDateFormat class by passing the required pattern of the date in String format to its constructor.
//Instantiating the SimpleDateFormat class SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy");
Format/convert the required Date object to String using the format() method, by passing it as a parameter.
//Formatting the obtained date String formattedDate = formatter.format(date);
Example
Following Java program formats the current date to a String and prints it.
import java.text.ParseException; import java.text.SimpleDateFormat; import java.time.LocalDate; import java.util.Date; public class DateToString { public static void main(String args[]) throws ParseException { //Retrieving the current date LocalDate localDate = LocalDate.now(); //Converting LocalDate object to Date Date date = java.sql.Date.valueOf(localDate); //Instantiating the SimpleDateFormat class SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy"); //Formatting the obtained date String formattedDate = formatter.format(date); System.out.println("Formatted date: "+formattedDate); } }
Output
Formatted date: 31-05-2019
- Related Articles
- How to Format a Date String using SimpleDateFormat in Java?
- How to format date string in PowerShell?
- How to format a string to date in as dd-MM-yyyy using java?
- Java Program to parse string date value with default format
- How to convert a date object to string with format hh:mm:ss in JavaScript?
- How to format date using printf() method in Java?
- How to format a date using the Gson library in Java?
- How to format a JavaScript date?
- Java Program to format a string
- How to parse Date from String in the format: dd/MM/yyyy to dd/MM/yyyy in java?
- How to convert String to Date in java?
- Program to convert Milliseconds to Date Format in Java
- Java Program to format date in mm-dd-yyyy hh:mm:ss format
- How to format date in JSP?
- How to convert a date format in MySQL?

Advertisements