如何将日期字符串格式化为所需的日期格式

我试图将字符串格式化为日期。

为此,我写了一个代码: –

Calendar cal = Calendar.getInstance(); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss"); System.out.println(sdf.format( cal.getTime() )); 

这很好..但现在我想将一个字符串转换为如上所述的日期..例如

 String dt="2010-10-22"; 

输出应该是这样的: – 2010-10-22T00:00:00

我该怎么做呢?

 String dt = "2010-10-22"; SimpleDateFormat sdfIn = new SimpleDateFormat("yyyy-MM-dd"); ParsePosition ps = new ParsePosition(0) Date date = sdfIn.parse(dt, pos) SimpleDateFormat sdfOut = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss"); System.out.println(sdfOut.format( date )); 

这应该为你做,记得把它包装在try-catch块以防万一。

 DateFormat dt = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss"); try { Date today = dt.parse("2010-10-22T00:00:00"); System.out.println("Your Date = " + dt.format(today)); } catch (ParseException e) { //This parse operation may not be successful, in which case you should handle the ParseException that gets thrown. //Black Magic Goes Here } 

如果您的输入将是ISO,您还可以查看使用Joda Time API ,如下所示:

 LocalDateTime localDateTime = new LocalDateTime("2010-10-22"); System.out.println("Formatted time: " + localDateTime.toString()); 

您用于输出日期格式的同一个类也可用于解析输入日期。

  • SimpleDateFormat参考

要使用您的示例,要解析示例日期:

 String dt = "2010-10-22"; SimpleDateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd"); System.out.println(dateFormatter.parse(dt)); 

未指定的字段(即小时,分钟等)将为0.因此,您可以使用相同的代码格式化输出日期。

日期格式示例

包含从一种格式到另一种格式的String Date对象的转换