Date Parse

From Java Example Source Code

Jump to: navigation, search

Contents

[edit] Overview - Date Parse

This Java program shows how to parse a string to Date.

[edit] Java Source Code

  • Package: example.calendardate
  • File: DateParse2.java
package example.calendardate;
 
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.Date;
 
/** Show some date uses */
public class DateParse2 {
    public static void main(String[] args) {
 
	// +
	SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
	String input[] = { "BD: 1913-10-01 Vancouver, B.C.", "MD: 1948-03-01 Ottawa, ON", "DD: 1983-06-06 Toronto, ON" };
	for (int i = 0; i < input.length; i++) {
	    String aLine = input[i];
	    String action;
	    switch (aLine.charAt(0)) {
	    case 'B':
		action = "Born";
		break;
	    case 'M':
		action = "Married";
		break;
	    case 'D':
		action = "Died";
		break;
	    // others...
	    default:
		System.err.println("Invalid code in " + aLine);
		continue;
	    }
	    int p = aLine.indexOf(' ');
	    ParsePosition pp = new ParsePosition(p);
	    Date d = formatter.parse(aLine, pp);
	    if (d == null) {
		System.err.println("Invalid date in " + aLine);
		continue;
	    }
	    String location = aLine.substring(pp.getIndex());
	    System.out.println(action + " on " + d + " in " + location);
	}
	// -
    }
}

[edit] What Result You Can Get

Run the program, you will get:


Born on Wed Oct 01 00:00:00 PST 1913 in  Vancouver, B.C.
Married on Mon Mar 01 00:00:00 PST 1948 in  Ottawa, ON
Died on Mon Jun 06 00:00:00 PDT 1983 in  Toronto, ON

[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.


Personal tools