Java java.text.ParseException: Unparseable date


用java將字符串轉換成Date類型是,會出現java.text.ParseException: Unparseable date異常。

例如下面的這段代碼就會出現上面的異常:

public boolean ratherDate(String date){
        try{
            SimpleDateFormat formate = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
            Date todayDate = formate.parse(formate.format(new Date()));
            Date targeDate = formate.parse(date);
                       if(Math.abs(((targeDate.getTime() - todayDate.getTime())/(24*3600*1000))) >= 0){
                return true;
            }
            return false;
        }catch(Exception e){
            e.printStackTrace();
        }
        return false;
    }

解決辦法有兩種:

一、Date targetDate = formate.parse(date.toString());

二、Date targetDate = (Date)formate.parseObject(date);

到此為止,問題解決

大家可以把下面這段代碼copy上去試試看。

public boolean ratherDate(String date){
        try{
            SimpleDateFormat formate = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
            Date todayDate = (Date)formate.parseObject(formate.format(new Date()));
            Date targeDate = (Date)formate.parseObject(date);
            //如果最晚預訂時間大於當前日期則允許訂購當日票
            if(Math.abs(((targeDate.getTime() - todayDate.getTime())/(24*3600*1000))) >= 0){
                return true;
            }
            return false;
        }catch(Exception e){
            e.printStackTrace();
        }
        return false;
    }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM