Wednesday 16 January 2019

How to format the date with different patterns using java.text.SimpleDateFormat class


Click here to watch on Youtube: 
https://www.youtube.com/watch?v=vpwvWdnILuo&list=UUhwKlOVR041tngjerWxVccw

SimpleDateFormatDemo.java

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

public class SimpleDateFormatDemo
{
    public static void main(String[] args)
    {

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

        /*
         * Parameters: pattern the pattern describing the date and
         * time format
         */

        SimpleDateFormat formatter = new SimpleDateFormat("MM/dd/yyyy");
        String strDate = formatter.format(date);
        System.out.println("Date Format with MM/dd/yyyy = " + strDate);

        formatter = new SimpleDateFormat("dd-MM-yyyy hh:mm:ss");
        strDate = formatter.format(date);
        System.out.println("Date Format with dd-MM-yyyy hh:mm:ss = " + strDate);

        formatter = new SimpleDateFormat("dd MMMM yyyy");
        strDate = formatter.format(date);
        System.out.println("Date Format with dd MMMM yyyy = " + strDate);

        formatter = new SimpleDateFormat("dd MMMM yyyy zzzz");
        strDate = formatter.format(date);
        System.out.println("Date Format with dd MMMM yyyy zzzz = " + strDate);

        formatter = new SimpleDateFormat("E, dd MMM yyyy hh:mm:ss z");
        strDate = formatter.format(date);
        System.out.println(
                "Date Format with E, dd MMM yyyy hh:mm:ss z : " + strDate);
    }

}

Output:

date = Tue Jan 08 15:39:16 IST 2019
Date Format with MM/dd/yyyy = 01/08/2019
Date Format with dd-MM-yyyy hh:mm:ss = 08-01-2019 03:39:16
Date Format with dd MMMM yyyy = 08 January 2019
Date Format with dd MMMM yyyy zzzz = 08 January 2019 India Standard Time
Date Format with E, dd MMM yyyy hh:mm:ss z : Tue, 08 Jan 2019 03:39:16 IST

Click the below link to download the code:
https://sites.google.com/site/javaspringram2019/java_spring_2019/SimpleDateFormatDemo_format_date_pattern.zip?attredirects=0&d=1

Github Link:
https://github.com/ramram43210/Java_Spring_2019/tree/master/Java_2019/SimpleDateFormatDemo_format_date_pattern

Bitbucket Link:
https://bitbucket.org/ramram43210/java_spring_2019/src/4327965661b34e0cc17880946800be5f5d73f2dd/Java_2019/SimpleDateFormatDemo_format_date_pattern/?at=master

See also:
  • All JavaEE Videos Playlist
  • All JavaEE Videos
  • All JAVA EE Links
  • Spring Tutorial
  • Servlets Tutorial
  • All Design Patterns Links
  • JDBC Tutorial
  • Java Collection Framework Tutorial
  • JAVA Tutorial
  • Kids Tutorial
  • Cooking Tutorial
  • No comments:

    Post a Comment