我的时间戳为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"));
}
我收到 java.lang.IllegalArgumentException 错误。可能是什么问题?
最佳答案
您的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
}
关于java - 将时间戳从一种格式转换为另一种格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29341918/