Java Date() 给出错误的日期 [英] Java Date() giving the wrong date

查看:39
本文介绍了Java Date() 给出错误的日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的方法,可以获取当前日期,将其转换为某种格式,然后将其作为字符串返回.到目前为止,它一直很好(上次尝试是在 1 月 31 日左右),但由于某种原因,当我今天尝试它时,它返回字符串2013-02-43".

I've got a simple method that should get the current date, put it into a certain format and then return it as a String. Up to this point it's been fine (last tried it on about 31st Jan) but for some reason when I tried it today it returns the String "2013-02-43".

现在显然 2 月没有 43 天,我不知道为什么它会返回这个.我到处寻找解决方案,但似乎没有一个适合我遇到的特定问题.代码如下:

Now obviously there aren't 43 days in February and I have no idea why it's returning this. I've searched everywhere I can for a solution but none of them seem to fit the specific problem I am having. Here is the code:

public String getDate(){
    DateFormat dateFormat = new SimpleDateFormat("YYYY-MM-DD");
    Date date = new Date();

    return dateFormat.format(date);
}

仅作为记录,我尝试使用 Calendar.getInstance() 等,结果相同.有趣的是当我尝试

Just for the record I've tried using Calendar.getInstance() etc. with the same result. Interestingly when I try

get(Calendar.DAY_OF_MONTH) 

返回的是 12,所以数字是正确的,但中间出现了问题.

it comes back with 12, so somewhere the numbers are right but something's going wrong in between.

谢谢

推荐答案

DD 表示年中的某天,而 dd 表示月中的某天.此外,Y 表示周年,而 y 表示年.您需要 yyyy-MM-dd(区分大小写).

DD means Day of Year, while dd means Day of Month. Also, Y means Week Year, while y means Year. You want yyyy-MM-dd (case-sensitive).

public String getDate(){
    DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
    Date date = new Date();

    return dateFormat.format(date);
}

这篇关于Java Date() 给出错误的日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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