LocalDateTime日期格式化和指定日期的时分秒
package com.example.core.mydemo.date;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
/**
* now=2023-06-30
* after=2023-07-04
* afterTime=2023-07-04T00:00:01
* dateFormat=06/30-07/01
*/
public class LocalDateTest {
public static final String YYYYMMDDHHMMSSS_PATTERN = "yyyyMMddHHmmss";
public static final String DEFAULT_PATTERN_NEW_SHORT = "MM/dd";
public static void main(String[] args) {
LocalDate now = LocalDate.now();
LocalDate after = now.plusDays(4);
LocalDateTime afterTime = after.atTime(0,0,1);
System.out.println("now=" + now);
System.out.println("after=" + after);
System.out.println("afterTime=" + afterTime);
String startTime = "20230630163000";
String endTime = "20230701163000";
LocalDateTime startLdt = parseStringToDateTime(startTime,YYYYMMDDHHMMSSS_PATTERN);
LocalDateTime endLdt = parseStringToDateTime(endTime,YYYYMMDDHHMMSSS_PATTERN);
String rentStr = formatDateTime(startLdt,DEFAULT_PATTERN_NEW_SHORT);
String revertStr = formatDateTime(endLdt,DEFAULT_PATTERN_NEW_SHORT);
String rentViewFormat = rentStr + "-" + revertStr;
System.out.println("dateFormat=" + rentViewFormat);
}
public static LocalDateTime parseStringToDateTime(String time, String format) {
DateTimeFormatter df = DateTimeFormatter.ofPattern(format);
return LocalDateTime.parse(time, df);
}
public static String formatDateTime(LocalDateTime dateTime, String pattern) {
if (dateTime == null) {
return null;
}
if (pattern == null || pattern.isEmpty()) {
pattern = YYYYMMDDHHMMSSS_PATTERN;
}
DateTimeFormatter formatter = DateTimeFormatter.ofPattern(pattern);
return dateTime.format(formatter);
}
}
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有