LocalDateTime相关日期时间类转换

package com.hcmony.sword.date;

import java.time.*;
import java.time.format.DateTimeFormatter;
import java.util.Date;

/**
 * <h3>此类方法基于LocalDateTime,LocalDate,LocalTime</h3>
 * <p></p>
 *
 * @author hcmony
 * @see LocalDateTime,LocalDate,java.time.LocalTime
 * @since V1.0.0, 2018/12/14 11:58
 */
public final class LocalDateTimeHelper {

	private LocalDateTimeHelper() {}

	/**
	 * 8位的时间格式
	 */
	public static final String PATTERN_STR8 = "yyyyMMdd";
	/**
	 * 10位时间格式
	 */
	public static final String PATTERN_STR10 = "yyyy-MM-dd";
	/**
	 * 14位时间格式
	 */
	public static final String PATTERN_STR14 = "yyyyMMddHHmmss";

	/**
	 * 23位时间格式
	 */
	public static final String PATTERN_STR17 = "yyyyMMddHHmmssSSS";

	/**
	 * 19位时间格式
	 */
	public static final String PATTERN_STR19 = "yyyy-MM-dd HH:mm:ss";

	/**
	 * 23位时间格式
	 */
	public static final String PATTERN_STR23 = "yyyy-MM-dd HH:mm:ss.SSS";

	/**
	 * yyyyMMdd
	 * @return
	 */
	public static String getDateStringNow() {
		return formatToString(PATTERN_STR8);
	}

	/**
	 *
	 * @param pattern
	 * @return
	 */
	public static String formatToString(String pattern) {
		return formatToString(LocalDateTime.now(),pattern);
	}

	/**
	 *
	 * @param pattern
	 * @return
	 */
	public static String formatToString(LocalDateTime localDateTime,String pattern) {
		return localDateTime.format(DateTimeFormatter.ofPattern(pattern));
	}


	public static void main(String[] args) {
		System.out.println(getDateStringNow());
		System.out.println(formatToString(PATTERN_STR10));
		System.out.println(formatToString(PATTERN_STR23));
		System.out.println(formatToString(PATTERN_STR14));
		System.out.println(formatToString(PATTERN_STR19));
		localDateTimeToDate(LocalDateTime.now());
		dateToLocalDateTime(new Date());
	}


	/**
	 * localDateTime转成date
	 * @param localDateTime
	 * @return
	 */
	public static Date localDateTimeToDate(LocalDateTime localDateTime){
		ZoneId zoneId = ZoneId.systemDefault();
		ZonedDateTime zdt = localDateTime.atZone(zoneId);
		return Date.from(zdt.toInstant());
	}

	/**
	 * localDateTime转成date
	 * @param date
	 * @return
	 */
	public static LocalDateTime dateToLocalDateTime(Date date){
		Instant instant = date.toInstant();
		ZoneId zoneId = ZoneId.systemDefault();
		return instant.atZone(zoneId).toLocalDateTime();
	}
}

 

上一篇:LocalDateTime与DateTimeFormatter


下一篇:乐字节-Java8新特性之Date API