不可稀释的日期:“30-Jun-12” [英] Unparseable date: "30-Jun-12"

查看:250
本文介绍了不可稀释的日期:“30-Jun-12”的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用Java方法将日期转换成适当的格式:

I'm using a Java method to convert the date into suitable format:

private Timestamp toTimeStamp(String s) throws java.text.ParseException
    {
        Timestamp ts = null;
        java.util.Date date = null;
        if (s == null || s.trim().isEmpty()) return ts;

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss.S");
        date = (java.util.Date) sdf.parse(s);
        ts = new Timestamp(date.getTime());

        return ts;

    }

当我尝试执行表单时,我收到此错误:

When I tried to execute the form I get this error:

Unparseable date: "30-Jun-12"

我尝试更改日期格式,但我仍然收到此错误。你可以帮我解决吗?

I tried to change the the date format but I still get this error. Can you help me to fix it?

推荐答案

有两个问题:


  1. 您的日期格式模式错误。 yyyy-MM-dd hh:mm:ss.S 永远不能匹配 30-Jun-12 。您需要 dd-MMM-yy 。另请参阅 SimpleDateFormat javadoc

  2. 解析日/月名称时,请确保指定与日/月名称中使用的语言相匹配的正确语言环境。您的系统默认地区似乎根本不是英文。

  1. Your date format pattern is wrong. The yyyy-MM-dd hh:mm:ss.S can never match 30-Jun-12. You need dd-MMM-yy. See also SimpleDateFormat javadoc.
  2. When parsing day/month names, make sure that you specify the right locale matching the language used in the day/month names. Your system default locale seems to be not English at all.

所以这应该做:

SimpleDateFormat sdf = new SimpleDateFormat("dd-MMM-yy", Locale.ENGLISH);
Date date = sdf.parse("30-Jun-12");

第三个问题,其实更是一个设计问题,你不应该使用<$ c $您的模型/业务层中的任何位置(您最初标记了JSF的问题)的任何地方的c> java.sql.Timestamp (和其他SQL特定的日期类型)。您只应在数据层中使用它。使用 java.util.Date ,只能在您需要坚持在数据库中的时刻转换,因此

A third problem, which is actually more a design matter, you should not be using java.sql.Timestamp (and other SQL specific date types) anywhere in your model/business layer (you originally tagged the question JSF). You should only use it in your data layer. Use java.util.Date instead and convert only at exactly the moment you need to persist it in the DB like so

preparedStatement.setTimestamp(1, new Timestamp(date.getTime()));

这篇关于不可稀释的日期:“30-Jun-12”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆