- Java Programming Examples
- Example - Home
- Example - Environment
- Example - Strings
- Example - Arrays
- Example - Date & Time
- Example - Methods
- Example - Files
- Example - Directories
- Example - Exceptions
- Example - Data Structure
- Example - Collections
- Example - Networking
- Example - Threading
- Example - Applets
- Example - Simple GUI
- Example - JDBC
- Example - Regular Exp
- Example - Apache PDF Box
- Example - Apache POI PPT
- Example - Apache POI Excel
- Example - Apache POI Word
- Example - OpenCV
- Example - Apache Tika
- Example - iText
- Java Tutorial
- Java - Tutorial
- Java Useful Resources
- Java - Quick Guide
- Java - Useful Resources
How to display date in different formats using Java
Problem Description
How to display date in different formats?
Solution
This example displays the names of the weekdays in short form with the help of DateFormatSymbols().getWeekdays() method of DateFormatSymbols class.
import java.text.*; import java.util.*; public class Main { public static void main(String[] args) { Date dt = new Date(1000000000000L); DateFormat[] dtformat = new DateFormat[6]; dtformat[0] = DateFormat.getInstance(); dtformat[1] = DateFormat.getDateInstance(); dtformat[2] = DateFormat.getDateInstance(DateFormat.MEDIUM); dtformat[3] = DateFormat.getDateInstance(DateFormat.FULL); dtformat[4] = DateFormat.getDateInstance(DateFormat.LONG); dtformat[5] = DateFormat.getDateInstance(DateFormat.SHORT); for(DateFormat dateform : dtformat) System.out.println(dateform.format(dt)); } }
Result
The above code sample will produce the following result.
9/9/01 7:16 AM Sep 9, 2001 Sep 9, 2001 Sunday, September 9, 2001 September 9, 2001 9/9/01
The following is an another sample example of date in another format.
import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Locale; public class SimpleDateFormatExample { public static void main(String[] args) { Date curDate = new Date(); SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd"); String DateToStr = format.format(curDate); System.out.println(DateToStr); format = new SimpleDateFormat("dd-M-yyyy hh:mm:ss"); DateToStr = format.format(curDate); System.out.println(DateToStr); format = new SimpleDateFormat("dd MMMM yyyy zzzz", Locale.ENGLISH); DateToStr = format.format(curDate); System.out.println(DateToStr); format = new SimpleDateFormat("E, dd MMM yyyy HH:mm:ss z"); DateToStr = format.format(curDate); System.out.println(DateToStr); try { Date strToDate = format.parse(DateToStr); System.out.println(strToDate); } catch (ParseException e) { e.printStackTrace(); } } }
The above code sample will produce the following result.
2016/11/11 11-11-2016 07:12:27 11 November 2016 Coordinated Universal Time Fri, 11 Nov 2016 07:12:27 UTC Fri Nov 11 07:12:27 UTC 2016
java_date_time.htm
Advertisements