SimpleDateFormat to combine formatting flags

In this chapter you will learn:

  1. How to combine formatting flags
  2. Add slash to separate fields

Combine formatting flags

The following code uses various format and displays date time value in various forms.

import java.text.SimpleDateFormat;
import java.util.Date;
/*from  ja v  a2  s  . c o m*/
public class Main{

  public static void main(String args[]) {
    Date date = new Date();
    SimpleDateFormat sdf;
    sdf = new SimpleDateFormat("yyyy.MM.dd G 'at' HH:mm:ss z");
    System.out.println(sdf.format(date));
    
    
    sdf = new SimpleDateFormat("EEE, MMM d, ''yy");
    System.out.println(sdf.format(date));
    
    
    sdf = new SimpleDateFormat("h:mm a");
    System.out.println(sdf.format(date));

    sdf = new SimpleDateFormat("hh 'o''clock' a, zzzz" );
    System.out.println(sdf.format(date));

    sdf = new SimpleDateFormat("K:mm a, z");
    System.out.println(sdf.format(date));

    sdf = new SimpleDateFormat("yyyyy.MMMMM.dd GGG hh:mm aaa");
    System.out.println(sdf.format(date));

    sdf = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss Z");
    System.out.println(sdf.format(date));

    sdf = new SimpleDateFormat("yyMMddHHmmssZ");
    System.out.println(sdf.format(date));

    sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
    System.out.println(sdf.format(date));

  }
}

The output:

Add slash to separate fields

MM/dd/yy uses slash to separate fields for different parts of date value and produces more meaning full string.

import java.util.Date;
import java.text.SimpleDateFormat;
//from   j a v  a 2 s  .c  om
public class Main {
  public static void main(String[] args) {
    Date date = new Date();
    SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yy");
    String strDate = sdf.format(date);
    System.out.println("formatted date in mm/dd/yy : " + strDate);

  }
}

The output:

The following code use dd/MM/yyyy.

import java.text.SimpleDateFormat;
import java.util.Date;
// j a va  2s  .c o m
public class Main {
  public static void main(String[] args) {
    Date date = new Date();
    SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
    String strDate = sdf.format(date);
    System.out.println("formatted date in dd/MM/yyyy : " + strDate);
    
  }
}

The output:

MM-dd-yyyy hh:mm:ss uses different separators.

import java.text.SimpleDateFormat;
import java.util.Date;
/*from  j  a v a 2s .c o  m*/
public class Main {
  public static void main(String[] args) {
    Date date = new Date();
    SimpleDateFormat sdf = new SimpleDateFormat("MM-dd-yyyy hh:mm:ss");
    String strDate = sdf.format(date);
    System.out.println("formatted date in MM-dd-yyyy hh:mm:ss:" + strDate);
    
  }
}

The output:

Next chapter...

What you will learn in the next chapter:

  1. Get to know TimeZone class
  2. TimeZone Creation