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

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

问题描述

我有一个简单的方法,应该得到当前的日期,把它放在一定的格式,然后返回它作为一个字符串。到目前为止,这是很好的(最后一次尝试在1月31日),但由于某些原因,当我今天尝试它返回字符串2013-02-43。



现在显然,在二月没有43天,我不知道为什么回来了。我已经搜索到我可以解决的任何地方,但没有一个似乎符合我正在遇到的具体问题。这是代码:

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

return dateFormat.format(date);
}

只是为了纪录我试过使用Calendar.getInstance()等结果相同。有趣的是,当我尝试

  get(Calendar.DAY_OF_MONTH)

它回来了12,所以在某个地方数字是正确的,但之间出现问题。



谢谢


解决方案

DD 表示年度日,而 dd 表示每月的一天。您需要 yyyy-MM-dd (区分大小写)。

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

return dateFormat.format(date);
}


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".

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);
}

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

get(Calendar.DAY_OF_MONTH) 

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

Thanks

解决方案

DD means Day of Year, while dd means Day of Month. 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天全站免登陆