![](/img/trans.png)
[英]How to convert java.util.Date with a given format to String instance?
[英]Convert string to date in Java for given format
我收到了 API 对日期字段的回复。
"billCycleDate":"2022-07-15T00:00:00-05:00"
我正在尝试将其转换为“dd-MM-yyyy”日期格式。 简单的方法是简单地从字符串中提取日期,然后转换成我想要的格式。 但我想知道是否有一种“正确”的方式来做到这一点。
以下代码是我一直在使用的:
inputFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss Z", Locale.ENGLISH);
DateTimeFormatter outputFormatter = DateTimeFormatter.ofPattern("dd-MM-yyy", Locale.ENGLISH);
LocalDate date = LocalDate.parse(localBill.getBillCycleDate(), inputFormatter);
formattedDate = outputFormatter.format(date);
我尝试了不同的模式(“yyyy-MM-dd'T'HH:mm:ss.SSSXXX”、“yyyy-MM-dd'T'HH:mm:ss.SSS'Z'”等)但是它们似乎都不起作用。 它抛出以下错误:
java.time.format.DateTimeParseException: Text '2022-07-15T00:00:00-05:00' could not be parsed at index 19
尝试这个
inputFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:sszzz", Locale.ENGLISH);
试试这个。
DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX");
df.setTimeZone(TimeZone.getTimeZone("UTC"));
try {
return df.parse(dateStr); // pass the string variable which contains the date and time.
// Make sure your string has milliseconds too. Lack of such line will lead to an erroneous value for millisecond.
} catch (ParseException e) {
e.printStackTrace();
}
让我知道是否需要任何帮助。
我不是 Android 开发人员,但我相信以下 [Java] 代码也适用于 Android。
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
public class Tester {
public static void main(String[] args) {
String str = "2022-07-15T00:00:00-05:00";
ZonedDateTime zdt = ZonedDateTime.parse(str, DateTimeFormatter.ISO_OFFSET_DATE_TIME);
System.out.println(zdt.format(DateTimeFormatter.ofPattern("dd-MM-yyyy", Locale.ENGLISH)));
}
}
运行上面的代码会打印以下内容:
15-07-2022
请参阅 [Android] 文档了解DateTimeFormatter和ZonedDateTime 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.