How to convert Date to String in Java
The Date class represents a precise moment in time, down to the millisecond. Serializable, Cloneable and Comparable interfaces are implemented by the Date class in java.util
package. It has constructors and methods for working with dates and times in Java. In Java, the "java.text.SimpleDateFormat"
package has methods for formatting and parsing date and time. The “SimpleDateFormat” is a concrete class that inherits the “java. text. DateFormat
” class for formatting and parsing dates. It’s interesting to note that formatting entails turning a date into a string, whereas parsing entails converting a string to a date. So let us start with the tutorial on How to convert Date to String in Java.
A data type is an attribute of data in computer science that tells the compiler or interpreter how the programmer intends to use the data. A data type limits the possible values for an expression, such as a variable or a function. It specifies how that data type’s values are saved in memory and what actions can be done on them. Integers, floating-point numbers, strings, characters, and other storage categories are included in data types.
What’s The Approach?
- Import “
java.text.DateFormat
”, “java.util
“ and “java.text.SimpleDateFormat
” package to the class.
- Create an Object of date class as
Date d= new Date();
- Also, make a
DateFormat
Object.
- Use the
Try
andCatch
to eliminate the errors.
- Create the String using
format
() function.
- Print the string.
Also read:- How to Convert String to Double in Java
Java Program to Convert Date to String:-
/* * TechDecode Tutorials * * How to Covert Date to String * */ import java.text.DateFormat; import java.util.*; import java.text.SimpleDateFormat; public class Date_to_String { public static void main(String args[]) { //Creating object of date class Date d = new Date(); //Creating a DateFormat of DD/MM/YYYY DateFormat d1 = new SimpleDateFormat("dd/MM/yyyy"); try { //format() method Formats a Date into a date string. String Sdate = d1.format(d); //Printing the string System.out.println("String in date format is: " + Sdate); } catch (Exception ex ){ System.out.println(ex); } } }
Output:-