Tuesday, May 4, 2010

Create a String Date from a Date Object in Java

To create a Date String from a java.util.Date Object we can use the SimpleDateFormat class to convert from a Date to String. The following code example demonstrates creating a Date String from a Date Object using several different SimpleDateFormat formatting String patterns.

import java.text.SimpleDateFormat;
import java.util.Date;

public class CreateDateStringFromDate {


public static void main(String[] args) {

Date now = new Date();

SimpleDateFormat s = new SimpleDateFormat("ddMMyyyy");
System.out.println(s.format(now));

s = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
System.out.println(s.format(now));

s = new SimpleDateFormat("yyyy/MM/dd");
System.out.println(s.format(now));

s = new SimpleDateFormat("yyyy-MM-dd");
System.out.println(s.format(now));

s = new SimpleDateFormat("dd.MM.yyyy");
System.out.println(s.format(now));

s = new SimpleDateFormat("MMddyyyy");
System.out.println(s.format(now));

}

}




Here is the output of the example code:
23062010
2010-06-23 17:30:53
2010/06/23
2010-06-23
23.06.2010
06232010

No comments: