Tutorials

Java Date Format


Java SimpleDateFormat


The java.text.SimpleDateFormat class extends java.text.DateFormat class

Just like its parent class, SimpleDateFormat class also provides method to format and parse the String in java.

 

Formatting means converting Date into String.

Parsing means converting String into Date.

Parsing example:

 

package Date;

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

public class ParseExample {

            public static void main(String[] args) throws ParseException {

                 String strDate = "12/23/2017";

                 SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
                 Date date = sdf.parse(strDate);

                 System.out.println("date: "+ date);
            }
}

 

Formatting example 1:

 

package Date;

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

public class FormatDate {

      public static void main(String[] args) {

            Date date = new Date();
            System.out.println("Original date: "+ date);

            SimpleDateFormat sdf = new SimpleDateFormat();
            String dateInStr = sdf.format(date);

            System.out.println("Date in String: "+ dateInStr);
      }
}

OUTPUT:

Original date: Sat Dec 23 21:50:32 IST 2017

Date in String: 12/23/17 9:50 PM

 

Formatting example 2:

 

package Date;

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

public class FormatDate {

      public static void main(String[] args) {

            Date date = new Date();
            System.out.println("Original date: "+ date);

            SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
            String dateInStr = sdf.format(date);

            System.out.println("Date in String: "+ dateInStr);
      }
}

OUTPUT:

Original date: Sat Dec 23 22:21:34 IST 2017

Date in String: 23/12/2017

 

Different formats that could be tried are:

 


Please Share this page
Views : 22
Like every other website we use cookies. By using our site you acknowledge that you have read and understand our Cookie Policy, Privacy Policy, and our Terms of Service. Learn more Got it!