Parsing Date that is read from file

2019-09-17 02:02发布

问题:

I have record in the file as 17 Dec 2010 17:02:24 17 Dec 2010 18:02:24. I am reading these from file.... my parser code is:

static SimpleDateFormat df = new SimpleDateFormat("dd MMM yyyy hh:mm:ss");

public static String DateFormat(String startdate) {

    String date = null;
    try {

        java.util.Date tDate = df.parse(startdate);

        df = new SimpleDateFormat("dd-MMM-yy hh:mm:ss a");
        String formatteddate = df.format(tDate).toUpperCase();

        return formatteddate;

    } catch (ParseException e) {
        System.out.println("Unable to Parse" + e);
    }
    return date;

}

but only first date format get parsed...then error will be unable to parse

回答1:

you are over writing the df value again with a different format (as shown below) in the DateFormat(...) method. df is a static variable so it will use this new format for sub sequent reads. Use a new local variable for "dd-MMM-yy hh:mm:ss a"

df = new SimpleDateFormat("dd-MMM-yy hh:mm:ss a");


回答2:

I hope this helps.

static SimpleDateFormat inputDateFormat = new SimpleDateFormat("dd MMM yyyy hh:mm:ss");
static SimpleDateFormat outputDateFormat = new SimpleDateFormat("dd-MMM-yy hh:mm:ss a");

    public static String getFormattedDate(String startdate) {

    String date = null;
    try {

        java.util.Date tDate = inputDateFormat.parse(startdate);

        String formatteddate = outputDateFormat.format(tDate).toUpperCase();

        return formatteddate;

    } catch (ParseException e) {
        System.out.println("Unable to Parse" + e);
    }
    return date;

}


回答3:

Your problem is that you're re-using df as Pangea stated.

static SimpleDateFormat df = new SimpleDateFormat("dd MMM yyyy hh:mm:ss");

public static String DateFormat(String startdate) {

    String date = null;
    try {

        java.util.Date tDate = df.parse(startdate);

        SimpleDateFormat outputDf = new SimpleDateFormat("dd-MMM-yy hh:mm:ss a");
        String formatteddate = outputDf.format(tDate).toUpperCase();

        return formatteddate;

    } catch (ParseException e) {
        System.out.println("Unable to Parse" + e);
    }
    return date;

}