gpt4 book ai didi

java - 从日期字符串中提取时间

转载 作者:IT老高 更新时间:2023-10-28 20:31:51 32 4
gpt4 key购买 nike

如何格式化 "2010-07-14 09:00:02" 日期字符串以仅描述 "9:00"

最佳答案

使用 DateTimeFormatter在日期字符串和真实 LocalDateTime 之间进行转换目的。以 LocalDateTime 为起点,您可以轻松地应用基于 the javadoc of the DateTimeFormatter 中定义的各种模式的格式。 .

String originalString = "2010-07-14 09:00:02";
LocalDateTime dateTime = LocalDateTime.parse(originalString, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
String newString = DateTimeFormatter.ofPattern("H:mm").format(dateTime); // 9:00

如果您尚未使用 Java 8 或更新版本,请使用 SimpleDateFormat在日期字符串和真实 Date 之间进行转换目的。以 Date 作为起点,您可以轻松地应用基于 the javadoc of the SimpleDateFormat 中定义的各种模式的格式。 .

String originalString = "2010-07-14 09:00:02";
Date date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(originalString);
String newString = new SimpleDateFormat("H:mm").format(date); // 9:00

关于java - 从日期字符串中提取时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3504986/

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