Create SimpleDateFormats from a String
From Java Example Source Code
Contents |
[edit] Overview - Create SimpleDateFormats from a String
This Java program shows how to create SimpleDateFormat from a string pattern.
[edit] Java Source Code
- Package: example.calendardate
- File: DateFormatFile.java
package example.calendardate; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.text.SimpleDateFormat; import java.util.Date; /** Create SimpleDateFormats from a string read from a file */ //Modified by Code Panda, http://java.exampleshow.com public class DateFormatFile { /** Today's Date */ Date dNow = new Date(); public static void main(String[] args) throws IOException { DateFormatFile df = new DateFormatFile(); BufferedReader is = new BufferedReader(new InputStreamReader(System.in)); String line; String tip = "Please input a date format pattern:"; System.out.println(tip); while ((line = is.readLine()) != null) { df.process(line); System.out.println(tip); } } /** Use a SimpleDateFormat - based on arg - to print the date your way. */ protected void process(String arg) { SimpleDateFormat formatter = new SimpleDateFormat(arg); System.out.println("FORMAT: " + arg); System.out.println("RESULT: " + formatter.format(dNow)); System.out.println(); } }
[edit] What Result You Can Get
Run the program, you will get:
Please input a date format pattern:
input a date pattern, such as:
yyyy-MM-dd
you will get:
Please input a date format pattern: yyyy-MM-dd FORMAT: yyyy-MM-dd RESULT: 2008-08-09 Please input a date format pattern:
and input another format pattern, such as:
yyyy-MM-dd HH:mm:ss
then you will get:
Please input a date format pattern: yyyy-MM-dd FORMAT: yyyy-MM-dd RESULT: 2008-08-09 Please input a date format pattern: yyyy-MM-dd HH:mm:ss FORMAT: yyyy-MM-dd HH:mm:ss RESULT: 2008-08-09 16:36:17 Please input a date format pattern:
[edit] Required External Libraries and/or Files for this Java Example
Need nothing.
[edit] How to Run this Java Example Program
We recommend running this Java example program with Eclipse.
For assistance in working with Eclipse, please see How to Run Java Program with Eclipse.
It's fairly easy.
[edit] Question & Answer
Any question?
Click edit and post your question or answer here.
