有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

给出错误答案的java数据格式

我正在使用下面的代码格式化日期。但当我以错误的格式提供数据时,它会产生意想不到的结果

DateFormat inputFormat = new SimpleDateFormat("yyyy/MM/dd");
DateFormat outputFormat = new SimpleDateFormat("yyyy-MM-dd");`

String dateVal = "3/8/2016 12:00:00 AM";

try {
    Date date = inputFormat.parse(dateVal);
    String formattedVal = outputFormat.format(date);
    System.out.println("formattedVal : "+formattedVal);
} catch (ParseException pe) {
    throw pe;
}

在上述情况下,输出为-formattedVal:0009-02-05

它不是抛出解析异常,而是解析值并给我一个不正确的输出。有人能帮我理解这种反常的行为吗


共 (4) 个答案

  1. # 1 楼答案

    阅读SimpleDateFormat的文档:

    Year: ... Any other numeric string, such as a one digit string, a three or more digit string, or a two digit string that isn't all digits (for example, "-1"), is interpreted literally. So "01/02/3" or "01/02/003" are parsed, using the same pattern, as Jan 2, 3 AD. Likewise, "01/02/-3" is parsed as Jan 2, 4 BC.

  2. # 2 楼答案

    SimpleDateFormat在内部使用Calendar对象。{}类有两种模式,宽松严格。默认情况下,在lenient模式下,它接受不同字段的超出范围的值,并通过调整其他字段对这些值进行规范化,在您的情况下,将年份字段提前大约五手半

    尝试将SimpleDateFormat日历实例设置为strict:

    inputFormat.setLenient(false);
    

    您真的应该使用java.time类,如果Java8不是一个选项,那么应该使用JodaTime

  3. # 3 楼答案

    日期解析器尽最大努力将给定字符串解析为日期

    此处3/8/2016以年/月/日格式解析,因此:

    • 年份=3
    • 月份=8-->;8个月等于0.667年
    • 日期=2016年-->;2016天约为5.5年

    所以年份=3+5.5=8.5+0.667=9.17。这是2009年2月5日

  4. # 4 楼答案

    public static void main(String[] args) {
            try {
    
                String dateVal = "3/8/2016 12:00:00 AM";
                DateFormat inputFormat = new SimpleDateFormat("d/M/yyyy hh:mm:ss a");//the pattern here need to bee equals the 'dateVal' format
    
                DateFormat outputFormat = new SimpleDateFormat("yyyy-MM-dd");
    
                Date date = inputFormat.parse(dateVal);
                String formattedVal = outputFormat.format(date);
                System.out.println("formattedVal : "+formattedVal);
            } catch (ParseException pe) {
                System.err.println("cannot parse date...");
            }
        }