Choose Your Language

Friday 11 March 2016

Date to String and String to Date using java

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;


public class DateFormatExample {

public static void main(String[] args) throws ParseException {
// TODO Auto-generated method stub
//String currentDateAsString = "Fri Apr 18 00:00:00 IST 2016";
Date currentDate = new Date();
//Date to String
String currentDateAsString=currentDate.toString();
System.out.println("String Date : "+currentDateAsString);
DateFormat dateFormatter = new SimpleDateFormat("E MMM dd HH:mm:ss Z yyyy");
//String to Date
currentDate = (Date)dateFormatter.parse(currentDateAsString);

System.out.println("Date Format : "+currentDate);
//Date to String
currentDateAsString=currentDate.toString();
System.out.println("String Date : "+currentDateAsString);
//String to Date
currentDate=dateFormatter.parse(currentDateAsString);
System.out.println("Date Format : "+currentDate);

Calendar calendar = Calendar.getInstance();
calendar.setTime(currentDate);
String customDateFormat = calendar.get(Calendar.DATE) + "-" + (calendar.get(Calendar.MONTH) + 1) + "-" +calendar.get(Calendar.YEAR);
System.out.println("Custom Date Format : " + customDateFormat);  

}

}