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.
- FULL
- LONG
- MEDIUM
- SHORT
- DEFAULT(Uses Medium as style)
Date Output |
Predefined Style |
Tuesday, June 30, 2016 | FULL |
June 30, 2009 | LONG |
Jun 30, 2009 | MEDIUM |
6/30/09 | SHORT |
Jun 30, 2009 | MEDIUM |
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.16 | dd.MM.yy |
16.04.2016 | dd.MM.yyyy |
16.Apr.2016 | dd.MMM.yyyy |
30.April.2009 | dd.MMMM.yyyy |
30.April.2009 23:23:23 (24 Hr format) | dd.MM.yyyy HH:mm:ss |
16.4.16 | dd.M.yy |
30.April.2009 23:23:23 (12 Hr format) | dd.MM.yyyy hh:mm:ss |
30.April.2009 23:23:23 PM | dd.MM.yyyy HH:mm:ss a |
30.April.2009 23:23:23 PM IST | dd.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