Unparseable date: “2019-03-27“

虽然开发多年,依然会遇到很多坑,很多知识并不是学以致用,而是实践出真知,譬如:

public static void main(String[] args) {
		try {
			String dateStr="2019-03-27";
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:MM:ss");
			Date date = sdf.parse(dateStr);
			System.out.println(date);
		} catch (ParseException e) {
			e.printStackTrace();
		}
	}

运行报错,如图:

 经过查找原因才知道,SimpleDateFormat只能格式化比自己精度长的时间,或者相同的时间精度,不能格式化比自己精度短的时间。正确的写法如下:

public static void main(String[] args) {
		try {
			String dateStr="2019-03-27 00:00:00";
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:MM:ss");
			Date date = sdf.parse(dateStr);
			System.out.println(date);
		} catch (ParseException e) {
			e.printStackTrace();
		}
	}

输出如下:

下面是将string转成timestamp的方法, 

    /**
     * string转换成timestamp
     * 
     * @param index
     * @return
     * @throws Exception
     */
    public static Timestamp getTimeStamp(String index) throws Exception
    {
        if (index == null || index.trim().equals(""))
        {
            return null;
        } else if (index.length() == 10)
        {
            index += " 00:00:00.000000000";
        } else if (index.length() == 19)
        {
            index += ".000000000";
        } else if (index.length() == 26)
        {
            index = index.substring(0, 10) + " " + index.substring(11, 13) + ":" + index.substring(14, 16) + ":" + index.substring(17, 19)
                        + ".000000000";
        }
        return Timestamp.valueOf(index);
    }

 

  • 5
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 8
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 8
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值