NumberFormatException while parsing date with SimpleDateFormat.parse()

前端 未结 7 1306
我寻月下人不归
我寻月下人不归 2020-12-08 07:11

Have a function that creates a time-only Date object. (why this is required is a long story which is irrelevant in this context but I need to compare to some stuff in XML wo

7条回答
  •  执念已碎
    2020-12-08 07:48

    While the correct answer is the one by Clockwork-Muse (the cause of the problems is the fact that SimpleDateFormat isn't thread safe) I just wanted to deliver another method of creating a time-only Date object:

    public static Date getCurrentTimeOnly() {
    
        Calendar rightNow = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
        int hour = rightNow.get(Calendar.HOUR_OF_DAY);
        int minute = rightNow.get(Calendar.MINUTE);
        int second = rightNow.get(Calendar.SECOND);
        int msecond = rightNow.get(Calendar.MILLISECOND);
    
        long millisSinceMidnight
                = (hour * 60 * 60 * 1000)
                + (minute * 60 * 1000)
                + (second * 1000)
                + (msecond);
        return new Date(millisSinceMidnight);
    }
    

    This method is somewhat more formally correct, i.e. it handles leap-seconds. It doesn't assume, like other methods, that all days since epoch has always had 24*60*60*1000 milliseconds in them.

    It doesn't however handle the case where the leap second is on the current day.

提交回复
热议问题