公司网站建设基本流程图,步骤流程图,品牌营销策划方案,智龙迷城 wordpress工作时遇到前端传的时间格式是2023-12-3 17:41:52#xff0c;和2023-1-1 17:41:52但是我想要的是2023-12-03 17:41:52和2023-01-01 17:41:52。下面给大家分享几个解决方法
方法一#xff1a; 找前端#xff01;让他改2023-12-3 17:41:52和2023-1-1 17:41:52但是我想要的是2023-12-03 17:41:52和2023-01-01 17:41:52。下面给大家分享几个解决方法
方法一 找前端让他改使劲改
方法二 使用Java 8中的DateTimeFormatter的parse()和format()方法以及LocalDateTime LocalDate和LocalTime来实现。下面这一行代码完美解决
DateTimeFormatter.ofPattern(yyyy[-]M[-]d H:mm:ss).parse(2023-11-1 17:41:52, LocalDateTime::from).format(DateTimeFormatter.ofPattern(yyyy-MM-dd H:mm:ss)) 演示
package org.example;import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;/*** author 不爱吃鱼* date 2023/11/2 9:25*/
public class Main {public static void main(String[] args) {//时间转换String a 2023-1-1 17:41:52;String b 2023-12-3 17:41:52;System.out.println(a Time(a)\nb Time(b));}public static String Time(String time){return DateTimeFormatter.ofPattern(yyyy[-]M[-]d H:mm:ss).parse(time, LocalDateTime::from).format(DateTimeFormatter.ofPattern(yyyy-MM-dd H:mm:ss));}
} 打印结果 这行代码首先定义了一个DateTimeFormatter使用yyyy[-]M[-]d H:mm:ss的格式其中方括号[-]表示可选的分隔符用于匹配不同的日期字符串格式。 然后使用parse()方法将时间字符串2023-12-3 17:41:52解析为LocalDateTime对象。这里使用了一个方法引用LocalDateTime::from从解析的结果中获取一个LocalDateTime对象。 最后使用format()方法将LocalDateTime对象格式化为指定的时间格式。这会将LocalDateTime对象转换为字符串使用DateTimeFormatter.ofPattern(yyyy-MM-dd H:mm:ss)指定了输出的时间格式。
这样就可以将不同格式的时间字符串转换为统一的输出格式