Tags

Jan 22, 2012

Java SimpleDateFormat class to convert a Java Date to a formatted String.

The Java SimpleDateFormat class provides lets you easily convert (a) between a Java String to a Date or (b) perform the opposite conversion, from a Java Date to a String.

In following example, we first retrieve current date   and then we'll create a Java SimpleDateFormat object to define the custom format  Here's the source code for a complete Java SimpleDateFormat example class 
import java.util.Date;
import java.text.SimpleDateFormat;
import java.util.Calendar;
/**
 * SimpleDateFormat example: Convert from a Date to a formatted String
*/
public class JavaSimpleDateFormatTest
{
  public static void main(String[] args)
  {
    // (1) get today's date
    Date today = Calendar.getInstance().getTime();
    // (2) create our date "formatter"
    SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd-hh.mm");
    // (3) create a new String using the date format we want
    String formatedDate = formatter.format(today);
   
    System.out.println("Folder Name = " + formatedDate );
  }
}
In this example, we specify custom date format looked like this:
yyyy-MM-dd-hh.mm
Formatted date output looks like this:
2012-01-06-08.23
Other custom date format
yyyy-MM-dd                 Output    2012-01-06    yyyyMMdd                   Output    20120106    EEE MMM dd hh:mm:ss yyyy   Output    Fri Jan 06 08:32:51 20   yyyy-MM-dd-hh.mm.ss                        output            2012-01-06-08.23.32

No comments:

Post a Comment