Java SimpleDateFormat在Date对象中返回错误的值 [英] Java SimpleDateFormat returning wrong value in Date object

查看:143
本文介绍了Java SimpleDateFormat在Date对象中返回错误的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图解析一个字符串来获取一个Date对象,但它总是返回Sun。 2012年12月30日。有没有人对我做错了什么想法?

I'm trying to parse a string to get a Date object, but it's always returning Sun. December 30, 2012 for the date. Does anyone have any ideas on what I'm doing wrong?

我使用YYYY-MM-dd格式的字符串使用相同的代码,它工作得很好,所以我不知道为什么要切换到这种格式会导致问题。

I was using the same code using strings in YYYY-MM-dd format and it worked just fine, so I'm not sure why switching to this format is causing issues.

 public static Date getDateObjFromStr(String dateStr)
{
    DateFormat formatter = new SimpleDateFormat("MM/dd/YYYY");
    Date dateObj;
    try {
        dateObj = formatter.parse(dateStr);
        return dateObj;
    } catch(Exception e) {
        return null;
    }
}

推荐答案

Y 表示周年。尝试使用 y

Y represents week year. Try using y instead

DateFormat formatter = new SimpleDateFormat("MM/dd/yyyy");

这篇关于Java SimpleDateFormat在Date对象中返回错误的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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