text
Format date in custom formats with SimpleDateFormat
This is an example of how to format a Date in custom formats, with the SimpleDateFormat. SimpleDateFormat can be used to format and parse dates. Formating a Date in custom format with the SimpleDateFormat implies that you should:
- Create a new Date.
- Create a new SimpleDateFormat, using a String pattern. The pattern describes the date and time format.
- Invoke the
format(Date date)API method to format the date into a date String. The API provides several examples of patterns that can be used to describe the format.
Let’s take a look at the code snippet that follows:
package com.javacodegeeks.snippets.core;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
public class FormatDateInCustomFormatsWithSimpleDateFormat {
public static void main(String[] args) {
Date now = new Date();
DateFormat sdf;
sdf = new SimpleDateFormat("MM/dd/yy");
String strDate = sdf.format(now);
System.out.println("Formatted date in mm/dd/yy is: " + strDate);
sdf = new SimpleDateFormat("dd/MM/yyyy");
strDate = sdf.format(now);
System.out.println("Formatted date in dd/MM/yyyy is: " + strDate);
sdf = new SimpleDateFormat("MM-dd-yyyy hh:mm:ss");
strDate = sdf.format(now);
System.out.println("Formatted date in mm-dd-yyyy hh:mm:ss is: " + strDate);
sdf = new SimpleDateFormat("EEE MMM dd HH:mm:ss 'EET' yyyy");
strDate = sdf.format(now);
System.out.println("Formatted date in EEE MMM dd HH:mm:ss 'EET' yyyy is: " + strDate);
}
}
Output:
Formatted date in mm/dd/yy is: 10/20/11
Formatted date in dd/MM/yyyy is: 20/10/2011
Formatted date in mm-dd-yyyy hh:mm:ss is: 10-20-2011 04:45:41
Formatted date in EEE MMM dd HH:mm:ss 'EET' yyyy is: Thu Oct 20 16:45:41 EET 2011
This was an example of how to format a Date in custom formats with the SimpleDateFormat in Java.
