一尘不染

Calendar.getInstance给出错误的日期

java

我创建了一些小的方法作为Util类,例如以下代码:

public class Util
{
  public static final String DATETIME_PATTERN="YYYY/MM/DD - HH:mm:ss";

  public static String getDateTime()
  {
    SimpleDateFormat sdf=new SimpleDateFormat(DATETIME_PATTERN);
    return sdf.format(getToday());
  }

  public static Date getToday()
  {
    //Calendar today=Calendar.getInstance(); //didn't help
    Calendar today=Calendar.getInstance(Locale.TAIWAN); //didn't fix
    //Calendar today=Calendar.getInstance(TimeZone.getTimeZone("GMT+08:00")); //didn't fix as well
    return today.getTime();
  }
}

并且,进行了非常简单的运行,如下所示:

//run in main class
System.out.println("Generating sitemap.xml, please wait..."+Util.getDateTime());

结果是一个很奇怪的日期-> 2017/07/187

//Console result:
Generating sitemap.xml, please wait...2017/07/187 - 15:27:21

搜索了类似的问题,并尝试了TimeZone,Locale,但没有帮助。有什么建议 ?


顺便说一句,这是我的环境:

  • Windows7 x86
  • JDK 1.8.0.131 x86
  • Oxygen corrosion of x86

阅读 389

收藏
2020-12-03

共1个答案

一尘不染

您格式化日期的方式有问题。尝试将其更改为此

  public static final String DATETIME_PATTERN="yyyy/MM/dd - HH:mm:ss";
2020-12-03