DateFormat不起作用?

String selectedDate = "2012-" + createdMonth + "-" + createdDay; SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); try { createdDate = dateFormat.parse(selectedDate); } catch (ParseException e1) { e1.printStackTrace(); } System.out.println(createdDate); 

基本上当我打印createdDate时,它会显示如下:Thu Mar 08 00:00:00 CST 2012

而不是这种格式的东西“yyyy-MM-dd”。 谢谢你!

parse方法返回一个java.util.Date ,这是toString()Date实现返回的内容。

您需要打印如下。 重点是你需要使用你在打印时创建的格式化程序对象。

 System.out.println(dateFormat.format(createdDate)); 

使用dateFormat.format(createdDate)

您似乎认为createdDate是一个Date对象,其格式为yyyy-MM-dd 。 它没有。 Date对象没有格式 – 它们只包含一个时间戳,就像数字只是数字一样,它们本身没有格式。

SimpleDateFormat对象用于将String解析为Date对象,或将Date对象格式化为String

如果您有Date对象并且希望以特定格式显示日期,则使用SimpleDateFormat对象将其转换为具有适当格式的String

 SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd"); String text = fmt.format(createdDate); System.out.println("Created: " + text); 

如果您打印Date对象而没有明确地格式化它,它将使用默认格式进行格式化,这就是为什么你看到Thu Mar 08 00:00:00 CST 2012

Date对象不会以某种方式记住您从中解析它的String的格式。