Vous n'avez pas encore compris le LocalDateTime de java8 ? Un article résout facilement vos problèmes

1. Assurez-vous de publier vos propres résultats de recherche sur mon propre blog

  1. Lorsque j'ai changé d'emploi pendant cette période, la nouvelle entreprise a utilisé beaucoup de sucre syntaxique java8. La semaine dernière, j'ai développé une exigence et utilisé des calculs de temps. À cause de ce calcul de temps, cela a pris deux heures. . . profondément honteux

  2. Java a été publié à 17, et je n'ai pas étudié le LocalDateTIme de java8. . . Cela semble un peu déraisonnable. J'ai regardé le code source à la maison le week-end et j'ai écrit une classe d'outils pour gagner du temps et des efforts dans le futur processus de développement.

2. Cette classe d'outils n'est pas nécessairement la meilleure, mais ce n'est certainement pas la pire

  • S'adapter à tous les fuseaux horaires, inspiré de ZoneId
public static final Map<String, String> SHORT_IDS = Map.ofEntries(
        entry("ACT", "Australia/Darwin"),
        entry("AET", "Australia/Sydney"),
        entry("AGT", "America/Argentina/Buenos_Aires"),
        entry("ART", "Africa/Cairo"),
        entry("AST", "America/Anchorage"),
        entry("BET", "America/Sao_Paulo"),
        entry("BST", "Asia/Dhaka"),
        entry("CAT", "Africa/Harare"),
        entry("CNT", "America/St_Johns"),
        entry("CST", "America/Chicago"),
        entry("CTT", "Asia/Shanghai"),
        entry("EAT", "Africa/Addis_Ababa"),
        entry("ECT", "Europe/Paris"),
        entry("IET", "America/Indiana/Indianapolis"),
        entry("IST", "Asia/Kolkata"),
        entry("JST", "Asia/Tokyo"),
        entry("MIT", "Pacific/Apia"),
        entry("NET", "Asia/Yerevan"),
        entry("NST", "Pacific/Auckland"),
        entry("PLT", "Asia/Karachi"),
        entry("PNT", "America/Phoenix"),
        entry("PRT", "America/Puerto_Rico"),
        entry("PST", "America/Los_Angeles"),
        entry("SST", "Pacific/Guadalcanal"),
        entry("VST", "Asia/Ho_Chi_Minh"),
        entry("EST", "-05:00"),
        entry("MST", "-07:00"),
        entry("HST", "-10:00")
    );
  • Dans le code source, ZoneId met tous les fuseaux horaires dans une carte, et je fais directement une énumération ici
public static enum LocalDateTimeType {
		/**
		 * Australia/Darwin
		 */
		ACT,
		/**
		 * Australia/Sydney
		 */
		AET,
		/**
		 * America/Argentina/Buenos_Aires
		 */
		AGT,
		/**
		 * Africa/Cairo
		 */
		ART,
		/**
		 * America/Anchorage
		 */
		AST,
		/**
		 * America/Sao_Paulo
		 */
		BET,
		/**
		 * Asia/Dhaka
		 */
		BST,
		/**
		 * Africa/Harare
		 */
		CAT,
		/**
		 * America/St_Johns
		 */
		CNT,
		/**
		 * America/Chicago
		 */
		CST,
		/**
		 * Asia/Shanghai
		 */
		CTT,
		/**
		 * Africa/Addis_Ababa
		 */
		EAT,
		/**
		 * Europe/Paris
		 */
		ECT,
		/**
		 * America/Indiana/Indianapolis
		 */
		IET,
		/**
		 * Asia/Kolkata
		 */
		IST,
		/**
		 * Asia/Tokyo
		 */
		JST,
		/**
		 * Pacific/Apia
		 */
		MIT,
		/**
		 * Asia/Yerevan
		 */
		NET,
		/**
		 * Pacific/Auckland
		 */
		NST,
		/**
		 * Asia/Karachi
		 */
		PLT,
		/**
		 * America/Phoenix
		 */
		PNT,
		/**
		 * America/Puerto_Rico
		 */
		PRT,
		/**
		 * America/Los_Angeles
		 */
		PST,
		/**
		 * Pacific/Guadalcanal
		 */
		SST,
		/**
		 * Asia/Ho_Chi_Minh
		 */
		VST,
		/**
		 * -05:00
		 */
		EST,
		/**
		 * -07:00
		 */
		MST,
		/**
		 * -10:00
		 */
		HST,
		NULL;

		private LocalDateTimeType() {
		}
	}
  • Renvoie l'heure correspondant au fuseau horaire par positionnement d'énumération
public ZoneId switchDate() {
			switch (this.type) {
				case ACT:
				case AET:
				case AGT:
				case ART:
				case AST:
				case BET:
				case BST:
				case CAT:
				case CNT:
				case CST:
				case CTT:
				case EAT:
				case ECT:
				case IET:
				case IST:
				case JST:
				case MIT:
				case NET:
				case NST:
				case PLT:
				case PNT:
				case PRT:
				case PST:
				case SST:
				case VST:
				case EST:
				case MST:
				case HST:
					return ZoneId.of(ZoneId.SHORT_IDS.get(type.toString()));
				case NULL:
				default:
					return ZoneId.of(ZoneId.systemDefault().getId());
			}
		}
  • Si la valeur d'énumération n'est pas transmise, la valeur par défaut est NULL et l'heure par défaut du système sera renvoyée
public DateSwitch() {
			this.type = LocalDateTimeType.NULL;
		}

La mise en œuvre complète est la suivante

package com.mxc.mockmvc.mockprojet.util;

import java.time.Duration;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.time.temporal.TemporalUnit;
import java.util.Date;

/**
 * @Project : mock-projet
 * @Package : com.mxc.mockmvc.mockprojet.util
 * @author : Terry
 * @email : [email protected]
 * @date : 2022年07月31日 6:33 PM
 */
public class LocalDateUtil {

	public static final String FORMAT_DEFAULT = "yyyyMMdd";
	public static final String FORMAT_HOUR = "yyyyMMddHH";
	public static final String FORMAT_ALL = "yyyy-MM-dd HH:mm:ss";
	public static final String FORMAT_MIN = "yyyy-MM-dd HH:mm";
	public static final String FORMAT_CHINESE = "yyyy年MM月dd日";
	public static final String FORMAT_ALL_M = "yyyy-MM-dd HH:mm:ss.SSS";
	public static final String FORMAT_SMALL = "yyyyMMddHHmmss";
	public static final String FORMAT_SMALL_L = "yyyyMMddHHmmssSSS";
	public static final String FORMAT_SMALL_HOUR = "yyyyMMddHH";
	public static final String FORMAT_SMALL_MIN = "yyyyMMddHHmm";
	public static final String FORMAT_SMALL_OTHER = "yyMMddHHmmss";
	public static final String FORMAT_DEFAULT_SMALL = "yyyy-MM-dd";
	public static final String FORMAT_TIME = "HH:mm:ss";
	public static final String FORMAT_CHINESE_REMOVE_YEAR = "MM月dd日";

	/**
	 * 秒 =》LocalDateTime
	 * @param seconds
	 * @param type 一般情况下指定为LocalDateUtil.LocalDateTimeType.CTT
	 * @return
	 */
	public static LocalDateTime secondsToLDT(Long seconds, LocalDateTimeType type) {
		LocalDateTime localDateTime = LocalDateTime.ofInstant(Instant.ofEpochSecond(seconds), new DateSwitch(type).switchDate());
		return localDateTime;
	}

	/**
	 * 秒 =》LocalDateTime
	 * @param seconds
	 * @return
	 */
	public static LocalDateTime secondsToDefaultLDT(Long seconds) {
		LocalDateTime localDateTime = LocalDateTime.ofInstant(Instant.ofEpochSecond(seconds), new DateSwitch().switchDate());
		return localDateTime;
	}

	/**
	 * 毫秒 =》LocalDateTime
	 * @param millSeconds
	 * @param type 一般情况下指定为LocalDateUtil.LocalDateTimeType.CTT
	 * @return
	 */
	public static LocalDateTime millSecondsToLDT(Long millSeconds, LocalDateTimeType type) {
		LocalDateTime localDateTime = LocalDateTime.ofInstant(Instant.ofEpochMilli(millSeconds), new DateSwitch(type).switchDate());
		return localDateTime;
	}

	/**
	 * 毫秒 =》LocalDateTime
	 * @param millSeconds
	 * @return
	 */
	public static LocalDateTime millSecondsToDefaultLDT(Long millSeconds) {
		LocalDateTime localDateTime = LocalDateTime.ofInstant(Instant.ofEpochMilli(millSeconds), new DateSwitch().switchDate());
		return localDateTime;
	}

	/**
	 * 两个LocalDateTime的Duration
	 * @param beginTime
	 * @param endTime
	 * @return
	 */
	public static Duration timeDuration(LocalDateTime beginTime, LocalDateTime endTime) {
		Duration dur = Duration.between(beginTime, endTime);
		return dur;
	}

	/**
	 * LocalDateTime 转 Date
	 * @param time
	 * @return
	 */
	public static Date convertDefaultLDTToDate(LocalDateTime time) {
		return Date.from(time.atZone(new DateSwitch().switchDate()).toInstant());
	}

	/**
	 * LocalDateTime 转 Date
	 * @param time
	 * @param type 一般情况下指定为LocalDateUtil.LocalDateTimeType.CTT
	 * @return
	 */
	public static Date convertLDTToDate(LocalDateTime time, LocalDateTimeType type) {
		return Date.from(time.atZone(new DateSwitch(type).switchDate()).toInstant());
	}

	/**
	 * 获取指定日期的毫秒
	 * @param time
	 * @return
	 */
	public static Long getMillSecondsByDefaultLDT(LocalDateTime time) {
		return time.atZone(new DateSwitch().switchDate()).toInstant().toEpochMilli();
	}

	/**
	 * 获取指定日期的毫秒
	 * @param time
	 * @param type 一般情况下指定为LocalDateUtil.LocalDateTimeType.CTT
	 * @return
	 */
	public static Long getMillSecondsByLDT(LocalDateTime time, LocalDateTimeType type) {
		return time.atZone(new DateSwitch(type).switchDate()).toInstant().toEpochMilli();
	}

	/**
	 * 获取指定日期的秒
	 * @param time
	 * @return
	 */
	public static Long getSecondsByDefaultLDT(LocalDateTime time) {
		return time.atZone(new DateSwitch().switchDate()).toInstant().getEpochSecond();
	}

	/**
	 * 获取指定日期的秒
	 * @param time
	 * @param type 一般情况下指定为LocalDateUtil.LocalDateTimeType.CTT
	 * @return
	 */
	public static Long getSecondsByLDT(LocalDateTime time, LocalDateTimeType type) {
		return time.atZone(new DateSwitch(type).switchDate()).toInstant().getEpochSecond();
	}

	/**
	 * 获取指定时间的指定格式
	 * @param time
	 * @param pattern
	 * @return
	 */
	public static String formatTime(LocalDateTime time, String pattern) {
		return time.format(DateTimeFormatter.ofPattern(pattern));
	}

	/**
	 * 日期加上一个数,根据field不同加不同值,field为ChronoUnit.*
	 * @param time
	 * @param number
	 * @param field
	 * @return
	 */
	public static LocalDateTime plus(LocalDateTime time, long number, TemporalUnit field) {
		return time.plus(number, field);
	}

	/**
	 * 日期减去一个数,根据field不同减不同值,field参数为ChronoUnit.*
	 * @param time
	 * @param number
	 * @param field
	 * @return
	 */
	public static LocalDateTime minus(LocalDateTime time, long number, TemporalUnit field) {
		return time.minus(number, field);
	}

	public static LocalDateTime convertStringToLDT(String timeStr, String pattern) {
		return LocalDateTime.parse(timeStr, DateTimeFormatter.ofPattern(pattern));
	}

	public static class DateSwitch {

		private LocalDateUtil.LocalDateTimeType type;

		public DateSwitch() {
			this.type = LocalDateTimeType.NULL;
		}

		public DateSwitch(LocalDateUtil.LocalDateTimeType type) {
			this.type = type;
		}

		public ZoneId switchDate() {
			switch (this.type) {
				case ACT:
				case AET:
				case AGT:
				case ART:
				case AST:
				case BET:
				case BST:
				case CAT:
				case CNT:
				case CST:
				case CTT:
				case EAT:
				case ECT:
				case IET:
				case IST:
				case JST:
				case MIT:
				case NET:
				case NST:
				case PLT:
				case PNT:
				case PRT:
				case PST:
				case SST:
				case VST:
				case EST:
				case MST:
				case HST:
					return ZoneId.of(ZoneId.SHORT_IDS.get(type.toString()));
				case NULL:
				default:
					return ZoneId.of(ZoneId.systemDefault().getId());
			}
		}
	}

	public static enum LocalDateTimeType {
		/**
		 * Australia/Darwin
		 */
		ACT,
		/**
		 * Australia/Sydney
		 */
		AET,
		/**
		 * America/Argentina/Buenos_Aires
		 */
		AGT,
		/**
		 * Africa/Cairo
		 */
		ART,
		/**
		 * America/Anchorage
		 */
		AST,
		/**
		 * America/Sao_Paulo
		 */
		BET,
		/**
		 * Asia/Dhaka
		 */
		BST,
		/**
		 * Africa/Harare
		 */
		CAT,
		/**
		 * America/St_Johns
		 */
		CNT,
		/**
		 * America/Chicago
		 */
		CST,
		/**
		 * Asia/Shanghai
		 */
		CTT,
		/**
		 * Africa/Addis_Ababa
		 */
		EAT,
		/**
		 * Europe/Paris
		 */
		ECT,
		/**
		 * America/Indiana/Indianapolis
		 */
		IET,
		/**
		 * Asia/Kolkata
		 */
		IST,
		/**
		 * Asia/Tokyo
		 */
		JST,
		/**
		 * Pacific/Apia
		 */
		MIT,
		/**
		 * Asia/Yerevan
		 */
		NET,
		/**
		 * Pacific/Auckland
		 */
		NST,
		/**
		 * Asia/Karachi
		 */
		PLT,
		/**
		 * America/Phoenix
		 */
		PNT,
		/**
		 * America/Puerto_Rico
		 */
		PRT,
		/**
		 * America/Los_Angeles
		 */
		PST,
		/**
		 * Pacific/Guadalcanal
		 */
		SST,
		/**
		 * Asia/Ho_Chi_Minh
		 */
		VST,
		/**
		 * -05:00
		 */
		EST,
		/**
		 * -07:00
		 */
		MST,
		/**
		 * -10:00
		 */
		HST,
		NULL;

		private LocalDateTimeType() {
		}
	}
}

Acho que você gosta

Origin blog.csdn.net/u011277745/article/details/126119738
Recomendado
Clasificación