将日期yyddmmhhmmss转换为yyyy-MM-dd' T' HH:mm:ss in java

时间:2014-10-01 14:56:27

标签: java date calendar date-formatting

如何转换以下内容

String date= "140929100526";// yyddmmhhmmss

String formatted = "2014-09-29'T'10:05:26"; // yyyy-MM-dd'T'HH:mm:ss

我首先尝试使用日历转换字符串到日期,然后格式化日期以获取所需的格式。但最后的字符串并不准确。这是我的代码:

Calendar cal = Calendar.getInstance(TimeZone.getTimeZone( "UTC" ) );
cal.set( Calendar.YEAR,Integer.parseInt( dateTime.substring( 0, 1 ) ) );
cal.set( Calendar.MONTH, 2000+Integer.parseInt( dateTime.substring( 2, 3) ) );
cal.set( Calendar.DAY_OF_MONTH, Integer.parseInt( dateTime.substring( 4, 6 ) ) );
cal.set( Calendar.HOUR_OF_DAY, Integer.parseInt( dateTime.substring( 6, 8 ) ) );
cal.set( Calendar.MINUTE, Integer.parseInt( dateTime.substring( 8, 10) ) );
cal.set( Calendar.SECOND, Integer.parseInt( dateTime.substring( 10, 11 ) ) );
Date time = cal.getTime();
System.out.println( "observationTime=" + time );

SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("dd-MM-yy'T'HH:mm:SS");
String  date = DATE_FORMAT.format(time);
System.out.println("Today in dd-MM-yy'T'HH:mm:SS : " + date);

最终结果不准确。

Time=Mon Sep 29 13:05:02 EAT 167
Today in dd-MM-yy'T'HH:mm:SS : 29-09-67T13:05:409

2 个答案:

答案 0 :(得分:1)

首先,您需要将格式化日期解析为SimpleDateFormat,并按照您喜欢的方式对其进行格式化

Here你有一个包含有关SimpleDateFormat信息的文档,它会告诉你更多有关下面代码中发生的事情的信息

解决方案:

String date= "140929100526";
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'''T'''HH:mm:ss");
Date dateParsed = new SimpleDateFormat("yyMMddHHmmss").parse(date);
System.out.print(dateFormat.format(dateParsed));

答案 1 :(得分:0)

使用一个SimpleDateFormat对象,将第一种类型的字符串解析为Date对象。然后使用另一个SimpleDateFormat对象,将Date对象(你得到的)格式化为第二种类型的字符串。

相关问题