Monday, March 3, 2014

Java Date examples

Convert Date to String.

 SimpleDateFormat sdf = new SimpleDateFormat("dd/M/yyyy");
 String date = sdf.format(new Date());
 System.out.println(date); //15/10/2013Example

Convert String to Date.

 SimpleDateFormat sdf = new SimpleDateFormat("dd-M-yyyy hh:mm:ss");
 String dateInString = "31-08-1982 10:20:56";
 Date date = sdf.parse(dateInString);
 System.out.println(date); //Tue Aug 31 10:20:56 SGT 1982

Get current date time

 SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
 Date date = new Date();
 System.out.println(dateFormat.format(date)); //2013/10/15 16:16:39

No comments:

Post a Comment