随笔 - 632  文章 - 17  评论 - 54  阅读 - 92万

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;
    }
复制代码

 

posted on   飘杨......  阅读(27461)  评论(0编辑  收藏  举报
编辑推荐:
· 没有源码,如何修改代码逻辑?
· 一个奇形怪状的面试题:Bean中的CHM要不要加volatile?
· [.NET]调用本地 Deepseek 模型
· 一个费力不讨好的项目,让我损失了近一半的绩效!
· .NET Core 托管堆内存泄露/CPU异常的常见思路
阅读排行:
· 微软正式发布.NET 10 Preview 1:开启下一代开发框架新篇章
· 没有源码,如何修改代码逻辑?
· NetPad:一个.NET开源、跨平台的C#编辑器
· PowerShell开发游戏 · 打蜜蜂
· 凌晨三点救火实录:Java内存泄漏的七个神坑,你至少踩过三个!
< 2025年2月 >
26 27 28 29 30 31 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 1
2 3 4 5 6 7 8

点击右上角即可分享
微信分享提示