gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 08:14:40 26 4
gpt4 key购买 nike

我的时间戳为 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com