【问题标题】:Calender and SimpleDateFormat outputting the wrong date [duplicate]日历和 SimpleDateFormat 输出错误的日期 [重复]
【发布时间】:2015-10-12 06:34:41
【问题描述】:

每当我执行此代码时

Calendar cal = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("D:M:Y");

System.out.println("Date Launched: " + "[" + sdf.format(cal.getTime()) + "]");

打印出来

 Date Launched: [285:10:2015] 

我怎样才能得到它,以便打印出实际日期,如[12/10/2015]

【问题讨论】:

  • 发帖前请先搜索 StackOverflow。这个问题已经被讨论了数百次。与其靠直觉解析模式代码,不如研究class documentation。并复制此处找到的许多示例中提供的工作代码。

标签: java date calendar simpledateformat


【解决方案1】:
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");//d small

SimpleDateFormat doc

【讨论】:

    【解决方案2】:

    您设置了错误的格式。

    代替:

    SimpleDateFormat sdf = new SimpleDateFormat("D:M:Y");
    

    用途:

    SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
    

    地点:

    y   Year            Year    1996; 96
    Y   Week year       Year    2009; 09
    M   Month in year   Month   July; Jul; 07
    w   Week in year    Number  27
    W   Week in month   Number  2
    D   Day in year     Number  189
    d   Day in month    Number  10
    

    您可以在 oracle 的文档 here 中阅读有关 SimpleDateFormat 的更多信息。

    【讨论】:

      【解决方案3】:

      使用

      SimpleDateFormat sdf = new SimpleDateFormat("d/M/Y");
      

      【讨论】:

        【解决方案4】:

        试试下面的代码

        SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
        

        符号“d”表示月份中的某一天

        符号“D”表示一年中的一天

        【讨论】:

          【解决方案5】:

          使用 dd/MM/yyyy 而不是 D:M:Y,这样您的代码看起来像

          Calendar cal = Calendar.getInstance();
          SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
          
          System.out.println("Date Launched: " + "[" + sdf.format(cal.getTime()) + "]");
          

          因为 D 给出了一年中的一天,而你想要一个月中的一天

          M 给出一年中的月份

          Y 表示年份

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2014-08-12
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2019-05-12
            • 1970-01-01
            相关资源
            最近更新 更多