Java Program to Convert String into Date Object and Date into String

Java program to convert String into Date object and Date into String:

The following Java program is used to convert Date from String into Date object and Date object to String.

String to Date Object,

Syntax: Strings=”28/01/2019″;

SimpleDateFormat sdf=new SimpleDateFormat(“dd/MM/yyyy”);

Date d=sdf.parse(s);

Get the date in String format and convert it into Date Object using parse() method. SimpleDateFormat is used to get Date in the particular format.

Date object to String,

Syntax: Date d1=new Date();

String s1=sdf1.format(d1);

The current date is obtained using date object and is converted to String using format() method.

stringformat.java

package com.candidjava.time;

import java.util.Date;
import java.text.ParseException;
import java.text.SimpleDateFormat;
public class StringFormat 
{
	public static void main(String[] args) throws ParseException 
	{
		//String to date 
		String s="28/01/2019";
		SimpleDateFormat sdf=new SimpleDateFormat("dd/MM/yyyy");
		Date d=sdf.parse(s);
		System.out.println(d);
		
		//date to string 
		SimpleDateFormat sdf1=new SimpleDateFormat("yyyy/MM/dd");
		Date d1=new Date();
		String s1=sdf1.format(d1);
		System.out.println(s1);
	}

}

Output:

Mon Jan 28 00:00:00 IST 2019
2019/01/07

Leave a Reply

Your email address will not be published. Required fields are marked *