如何使用 SimpleDateFormat 将字符串转换为日期? [英] How to convert a String to a Date using SimpleDateFormat?

查看:43
本文介绍了如何使用 SimpleDateFormat 将字符串转换为日期?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个代码片段:

DateFormat formatter1;
formatter1 = new SimpleDateFormat("mm/DD/yyyy");
System.out.println((Date)formatter1.parse("08/16/2011"));

当我运行这个时,我得到这个作为输出:

When I run this, I get this as the output:

Sun Jan 16 00:10:00 IST 2011

我期望:

Tue Aug 16 "Whatever Time" IST 2011

我的意思是说我没有按预期得到这个月.什么错误?

I mean to say I am not getting the month as expected. What is the mistake?

推荐答案

试试这个:

new SimpleDateFormat("MM/dd/yyyy")

  • MM 是月"(不是 mm)
  • dd 是天"(不是 DD)
    • MM is "month" (not mm)
    • dd is "day" (not DD)
    • 一切都在SimpleDateFormat的javadoc


      仅供参考,您的格式仍然是有效日期格式的原因是:


      FYI, the reason your format is still a valid date format is that:

      • mm 是分钟"
      • DD 是一年中的一天"
      • mm is "minutes"
      • DD is "day in year"

      此外,您不需要将转换为 Date...它已经一个 Date(或者它会爆炸):

      Also, you don't need the cast to Date... it already is a Date (or it explodes):

      public static void main(String[] args) throws ParseException {
          System.out.println(new SimpleDateFormat("MM/dd/yyyy").parse("08/16/2011"));
      }
      

      输出:

      Tue Aug 16 00:00:00 EST 2011
      

      瞧!

      这篇关于如何使用 SimpleDateFormat 将字符串转换为日期?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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