用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; }