Java Date format

Here i will provide list of Java Date formats that are used in Java frequently. There are different ways you can achieve the same result in Java.

1- Using Predefined Format

You can directly use DateFormat class to format date in predefined style. DateFormat has predefined 4 styles which can be used for quick formatting instead of using SimpleDateFormat.

  1. FULL
  2. LONG
  3. MEDIUM
  4. SHORT
  5. DEFAULT(Uses Medium as style)

Date Output

Predefined Style

Tuesday, June 30, 2016FULL
June 30, 2009LONG
Jun 30, 2009MEDIUM
6/30/09SHORT
Jun 30, 2009MEDIUM

Example Code

package com.jbt;

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

public class DateFormate {
	public static void main(String[] args)
			throws ParseException {
		Date today;
		String strDate;
		DateFormat dateFormat;

		dateFormat = DateFormat
				.getDateInstance(DateFormat.LONG);
		today = new Date();
		strDate = dateFormat.format(today);

		System.out.println(strDate);
	}
}

Output

17 April, 2016

2- Using SimpleDateFormat

Date Output

Date Pattern

16.04.16dd.MM.yy
16.04.2016dd.MM.yyyy
16.Apr.2016dd.MMM.yyyy
30.April.2009dd.MMMM.yyyy
30.April.2009 23:23:23 (24 Hr format)dd.MM.yyyy HH:mm:ss
16.4.16dd.M.yy
30.April.2009 23:23:23 (12 Hr format)dd.MM.yyyy hh:mm:ss
30.April.2009 23:23:23 PMdd.MM.yyyy HH:mm:ss a
30.April.2009 23:23:23 PM ISTdd.MM.yyyy HH:mm:ss a z

Example Code

package com.jbt;

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

public class DateFormat {
	public static void main(String[] args) {
		String datePattern = "dd.MM.yyyy";
		Date today;
		String dateOutput;
		SimpleDateFormat simpleDateFormat;

		simpleDateFormat = new SimpleDateFormat(datePattern);
		today = new Date();
		dateOutput = simpleDateFormat.format(today);
		System.out.println(datePattern + " - " + dateOutput);
	}
}

Output

dd.MM.yyyy - 17.04.2016

3- Using Formatter Pattern

Formatter class can be used to support formatting of numeric, string and other variable types. Date can be formatted in different styles using this class. Some predefined conversion characters can be used to format date object.

Date Output

Date Pattern

04/17/16%tm/%td/%ty
2016-04-17%tY-%tm-%td
04/17/16%tF
2016-04-17%tD

Example Code

package com.jbt;

import java.util.Date;

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

		String datePattern = "%tY-%tm-%td";
		String datePattern1 = "%tF";
		Date today;
		String dateOutput;
		today = new Date();

		dateOutput = String.format(datePattern, today,
				today, today);
		System.out.println(dateOutput);

		dateOutput = String.format(datePattern1, today);
		System.out.println(dateOutput);
	}
}

Output

2016-04-17
2016-04-17

 

References

  1. Simple Date Format Java Doc
  2. Formatter Java Doc
  3. Java Date Format Complete list
By | 2017-07-22T23:04:20+00:00 April 16th, 2016|Code Base|0 Comments

About the Author:

Leave A Comment