If I have several Strings formatted differently do I need a separate instance of DateFormat to parse each String?

79 views Asked by At

I am trying to learn the ins and outs of DateFormat's parse() and format() methods for the SCJP 6 exam. I recently tried to make some code to format and parse dates and found that the parse method only works if a String is formatted in the way that matches the DateFormat instance's format. Does that mean that if I was using this class in real life and reading a document that had dates formatted in 6 different ways that I would need 6 different DateFormat objects to successfully parse the strings into date objects?

import java.util.*;
import java.text.*;
import java.io.Console;

class PlayWithDates {
    public static void main(String[] args) {
    String formatted = "";
    Date parsed;
    Date d1 = new Date();
    DateFormat defaultFormat = DateFormat.getDateInstance();
    DateFormat shortFormat = DateFormat.getDateInstance(DateFormat.SHORT);
    formatted = defaultFormat.format(d1);
    System.out.println(formatted);
    formatted = shortFormat.format(d1);
    System.out.println(formatted instanceof String);
    System.out.println(formatted);  

    try {
        parsed = shortFormat.parse(formatted);
        System.out.println(parsed); 
    } catch(ParseException pe) {
        System.out.println(pe);
    }
    try {
        parsed = defaultFormat.parse(formatted);
        System.out.println(parsed); 
    } catch(ParseException pe) {
        System.out.println(pe);
    }
    }
}

When I run this program I get:

Dec 11, 2013
true
12/11/13
Wed Dec 11 00:00:00 MST 2013
java.text.ParseException: Unparseable date: "12/11/13"

It seems to me that it would be very difficult to predict when a String would be parseable or not. Should I be somehow doing this with a Calendar instance? Thanks for any explanations. I'm going a bit crazy studying for this exam.

1

There are 1 answers

1
AlexR On BEST ANSWER

Since SimpleDateFormat accepts format specification in constructor you need separate instance of this class for each format.