将时间戳从一种格式转换为另一种格式

ank*_*t f 2 java

我的时间戳为2015-02-12T12:47:17.101+05:30. 在java中,我只想得到MMM_dd_yyyy。我尝试使用 SimpleDateFormat 类。但我无法得到它。你能告诉我如何获取月、日和年吗? 更新:

public static void main(String[] a ) {
 SimpleDateFormat sdf = new SimpleDateFormat("MMM_dd_yyyy");
 System.out.println(sdf.format("2015-02-12T12:47:17.101+05:30"));
}
Run Code Online (Sandbox Code Playgroud)

我收到 java.lang.IllegalArgumentException 错误。可能是什么问题?

Joe*_*ckx 5

SimpleDateFormat唯一的格式日期和时间戳。你正在传递一个String.

要正确执行此操作,请首先将您拥有的字符串解析为日期。然后使用格式化程序对其进行格式化。

//Java 7 and above
try {
  SimpleDateFormat inputFormat = new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ss.SSSX");
  Date date
  date = inputFormat.parse("2015-02-12T12:47:17.101+05:30");
  SimpleDateFormat outputFormat = new SimpleDateFormat("MMM_dd_yyyy");
  System.out.println(outputFormat.format(date));
}catch(Exception e){
  //cannot happen in this example
}
Run Code Online (Sandbox Code Playgroud)