Thursday 6 March 2014

Simple Date Formats and Converting a string to a particular date format wilth all the Date Format Definations in Java


SimpleDateFormat is a Java class that handles the date fromats. There are some basic rules followed in defining the custom date fromat.

E  - represents first 3 letters of the day of the week like (Ex: Sun, Mon, Tue etc..)

EEEE - represents the full name of the day (Ex: Sunday, Monday etc..)

yy - represents the last two digits of the year (Ex: 14 for 2014)

yyyy - represents the year (Ex: 2013,2014 etc..)

M - represents the month number (Ex: 1 for January, 2 for February, 11 for November etc..)

MM - represents the month in number with a preceded 0 (Ex: 01 for January, 02 fro February etc..)

MMM - represents the month in text with first 3 characters of the month (Ex: Jan, Feb, Mar Apr etc..)

MMMM or M's >3 - represents the full text of the month (Ex: January, February, March etc)

dd - represents the day in number with preceding zero for numbers less than 10. (Ex: 01, 02 etc..)
          (increasing each d will put a preceding 0 for example for ddd 1  becomes 001 which is not used as  the day are not more than 31 in a month)

H - represents the number of hour in 24 hours format (Ex: 1,2, 12 18, 24 etc..)

HH - represents the hour in 24 hours format with the preceding 0 (Ex: 01,02,03, 18,24 etc..)

h - represents the hour in 12 hours format ((Ex: 1,2, 12 etc..)

hh - represents the hour in 12 hours format with the preceding 0 (Ex: 01,02,03,12 etc..)

m - represents the minutes (Ex: 1, 2, 3, 59 etc..)

mm - represents the minutes with preceding 0. (Ex: 01, 02, 03, 59 etc..)

ss - for seconds withe preceding 0 (Ex: 01, 02, 03, 59 etc..)

a - represents the AM/PM.

z or zz or zzz - represents the 3 lettered Time Zone (Ex: CST, UST, IST etc..)

zzzz - represents the full Time Zone name (Ex: Central Standard Time, Indian Standard Time etc..)


Example:
Here is an example code for the Date formats.
The special characters are used for the user readable format users can put what they like most.

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

public class HelloWorld{

     public static void main(String []args){
        System.out.println("Simple Date Format test program");
       
        SimpleDateFormat sd=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss zzzz");
        Date now =new Date(); //The object new will have the current date
       
        System.out.println(now);
        System.out.println(sd.format(now));
       
     }
}


No comments: