Search code examples
javastringdatestring-parsing

Difficulty while converting string(date) to milliseconds In java


I have the following code. I am passing start = "2016/01/01 23:59:59" and end = "2017/01/01 23:59:59"

func(String start, String end) {

    SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
    Date date1 = sdf1.parse(start);
    long startTime = date1.getTime();
    \\System.out.println(startTime);

    SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
    Date date2 = sdf2.parse(end);
    long endTime = date2.getTime();
    \\System.out.println(endTime);

}

I am getting the following error

error: unreported exception ParseException; must be caught or declared to be thrown Date date = sdf.parse(time); ^

How do I rectify this ? And also, Why is it showing me this error ?


Solution

  • The DateFormat#parse() methods throws a ParseException. This means that if something goes wrong when parsing a string into a date, this exception may be thrown.

    One fix is to just declare your method to throw this exception, e.g.

    public long yourMethod() throws ParseException {
        SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
        Date date1 = sdf1.parse(start);
        long startTime = date1.getTime();
    
        return startTime;
    }
    

    Or, also taking the advice from the error message, you could place the code into a try catch block:

    public long yourMethod() {
        long startTime = -1L;
        try {
            SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
            Date date1 = sdf1.parse(start);
            startTime = date1.getTime();
        }
        catch (ParseException e) {
            // something went wrong
        }
    
        return startTime;
    }