LocalDateTime最常用方法和时间转换

前言:

Java 8 版本以后,新增了了LocalDateTime和了LocalDate类,转换方便不亚于jodaTIme。LocalDateTime方法有很多,本文将开发中最常用的一些时间转换列举出来,并给出转换后的示例,希望大家可以转换时参考使用。

字符串转LocalDateTime


public static LocalDateTime parseStringToDateTime(String time, String format) {
  DateTimeFormatter df = DateTimeFormatter.ofPattern(format);
  return LocalDateTime.parse(time, df);
}

LocalDateTime转字符串

public static String getDateTimeToString(LocalDateTime localDateTime, String format) {
  DateTimeFormatter formatter = DateTimeFormatter.ofPattern(format);
  return localDateTime.format(formatter);
}

测试:

若毫秒位不为000则显示毫秒

String utc = getUTCMillisecondFromTimestamp(1539718265123);
System.out.println(utc);

输出:2018-10-16T19:31:05.123Z

若毫秒为000则不显示毫秒,

String utc = getUTCMillisecondFromTimestamp(1539718265000);
System.out.println(utc);

输出:2018-10-16T19:31:05Z

Long型时间戳(15位)转UTC时间字符串

/**
	 * 将UTC时间戳转为UTC字符串(精确到秒)
	 *
	 * @param timestamp
	 * @return
	 */
	public static String getUTCStrFromTimestamp(long timestamp) {
		DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss'Z'");
		// 北京时间:ZoneId.of("UTC+8");系统默认时间:ZoneId.systemDefault() 
		LocalDateTime localDateTime = LocalDateTime.ofInstant(Instant.ofEpochMilli(timestamp), ZoneId.of("UTC"));
		String utc = localDateTime.format(formatter);
		return utc;
	}

测试:

String utc = getUTCStrFromTimestamp(1539718265123);
System.out.println(utc);

输出:2018-10-16T19:31:05Z

Long型时间戳(15位)转UTC时间字符串

	/**
	 * 将时间戳转为UTC字符串(若毫秒为000则不显示毫秒,若毫秒位不为000则显示毫秒)
	 * 
	 * 返回格式:2018-10-16T19:31:05.123Z
	 * 
	 * @param timestamp
	 * @return
	 */
	public static String getUTCMillisecondFromTimestamp(long timestamp) {
		Instant instant = Instant.ofEpochMilli(timestamp);
		String utcString = instant.toString();
		return utcString;
	}

获取今天的起止时间

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss'Z'");

String startTime = LocalDateTime.now().withHour(0).withMinute(0).withSecond(0).withNano(0).format(formatter);

String endTime = LocalDateTime.now().withHour(23).withMinute(59).withSecond(59).withNano(999_999_999).format(formatter);

返回目标月份的最后一天

/**
	 * 返回目标月份的最后一天
	 *
	 * @param sourceDate  目标月份
	 * @param monthOffset 月份偏移量
	 * @return
	 */
	private LocalDate getLastDateOfMonth(LocalDate sourceDate, int monthOffset) {
		return sourceDate.plusMonths(monthOffset).with(TemporalAdjusters.lastDayOfMonth());
	}

获取某天的起止时间(优雅)

LocalDate date = LocalDate.of(2021, 4, 20);
LocalDateTime startTime = LocalDateTime.of(date, LocalTime.MIN);
LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);

LocalDateTime设置自定义时间

/**
	 * 获得一个(毫秒)时间戳的十分钟起始时间戳
	 * 
	 * 如:输入1534930875000(2018-08-22 17:41:15)的时间戳返回1534930800000(2018-08-22 17:40:00)的时间戳
	 * 
	 * @param timestrap
	 * 
	 * 
	 * @return
	 */
	public static long getTenMinuteStartTimestrap(long timestamp) {
		LocalDateTime localDateTime = getLocalDateTimeByTimestamp(timestamp);
		int minute = localDateTime.getMinute();
		// 分钟个位数置为0
		int minute_floor = minute / 10 * 10;
		LocalDateTime startLocalDateTime = localDateTime.withMinute(minute_floor).withSecond(0).withNano(0);
		long startTimestamp = getTimestampByLocalDateTime(startLocalDateTime);
		return startTimestamp;
	}

Long毫秒时间戳转LocalDateTime

	/**
	 * Long毫秒时间戳转LocalDateTime
	 */
	public static LocalDateTime getLocalDateTimeByTimestamp(long timestamp) {
		Instant instant = Instant.ofEpochMilli(timestamp);
		LocalDateTime localDateTime = LocalDateTime.ofInstant(instant, ZoneOffset.UTC);
		return localDateTime;
	}

根据LocalDateTime获取毫秒时间戳


	/**
	 * 根据毫秒时间戳获取LocalDateTime
	 * @param localDateTime
	 * @return
	 */
	public static long getTimestampByLocalDateTime(LocalDateTime localDateTime) {
		long timestamp = localDateTime.atZone(ZoneId.of("UTC")).toInstant().toEpochMilli();
		return timestamp;
	}

Long时间戳根据时区转为当地日期

/**
	 * 时间戳根据时区转为当地日期
	 * @param timestamp
	 * @param timezone
	 * @return
	 */
	public static Date getLocalDateByTimezone(long timestamp, int timezone) {
		Instant instant = Instant.ofEpochMilli(timestamp);
		LocalDateTime localDateTime = LocalDateTime.ofInstant(instant, ZoneOffset.UTC);
		// 当地时间
		LocalDateTime localDate = localDateTime.plusHours(timezone);
		DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss'Z'");
		String localDateTimeStr = df.format(localDate);
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
		Date date = null;
		try {
			date = sdf.parse(localDateTimeStr);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return date;
	}

LocalDateTime转Date

注意:系统所在时区

Date date = Date.from(LocalDateTime.now().atZone(ZoneId.systemDefault()).toInstant());

Date转LocalDateTime

Date todayDate = new Date();
LocalDateTime ldt = todayDate.toInstant()
        .atZone( ZoneId.systemDefault() )
        .toLocalDateTime();

毫秒转秒(时间戳)

long second = Instant.ofEpochMilli(1636338645000L).getEpochSecond();

秒转毫秒(时间戳)

long second = Instant.ofEpochSecond(1636338645L).toEpochMilli();

总结

以后会将其他常用的方法,不断补充在此处。有需要的可以先收藏。

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
unit uTimeZonesMgr; interface uses Windows, SysUtils, Classes, Registry, DateUtils; type {* 用于读取时区注册表TZI(长度为44)的属性值,存储时区信息 *} PRegTZIInfo = ^TRegTZIInfo; TRegTZIInfo = record Bias: Longint; StandardBias: Longint; DaylightBias: Longint; StandardDate: TSystemTime; DaylightDate: TSystemTime; end; {* 单个时区管理对象 *} TTimeZone = class private FTimeZoneName: string; //时区的显示名 FDisplay: string; //夏令时的名字 FDlt: string; //时区标准名字 FStd: string; //是Time zone information的缩写,描述时区的一些重要信息 FTZI: PRegTZIInfo; function GetSelfTimeZoneInformation: TTimeZoneInformation; public constructor Create; destructor Destroy; override; function UTCToLocalDateTime(const AUTC: TDateTime; var ALocalDateTime: TDateTime): Boolean; function LocalDateTimeToUTC(const ALocalDateTime: TDateTime; var AUTC: TDateTime): Boolean; public property TimeZoneName: string read FTimeZoneName write FTimeZoneName; property Display: string read FDisplay write FDisplay; property Dlt: string read FDlt write FDlt; property Std: string read FStd write FStd; property TZI: PRegTZIInfo read FTZI write FTZI; end; {* 所有时区管理对象 *} TTimeZones = class private FTimeZoneKeyPath: string; FTimeZoneList: TStringList; FDefaultTimeZone: TTimeZone; procedure CollectTimeZone; procedure DestoryTimeZones; procedure CheckISDefaultTimeZone(ATimeZone: TTimeZone); public constructor Create; destructor Destroy; override; function FindTimeZone(const ADisplay: string): TTimeZone; public property TimeZoneList: TStringList read FTimeZoneList; property DefaultTimeZone: TTimeZone read FDefaultTimeZone; end; implementation { TTimeZones } procedure TTimeZones.CheckISDefaultTimeZone(ATimeZone: TTimeZone); var DefaultTimeZone: TTimeZoneInformation; begin GetTimeZoneInformation(DefaultTimeZone); if (ATimeZone.TZI.Bias = DefaultTimeZone.Bias) and (ATimeZone.Std = DefaultTimeZone.StandardName) then FDefaultTimeZone := ATimeZone; end; procedure TTimeZones.CollectTimeZone; var reg, tempReg: TRegistry; tempKeyPath: string; tempTimeZoneStrings: TStrings; iCir: Integer; tempTimeZone: TTimeZone; begin reg := TRegistry.Create; try reg.RootKey := HKEY_LOCAL_MACHINE; reg.OpenKey(FTimeZoneKeyPath, False); tempTimeZoneStrings := TStringList.Create; try reg.GetKeyNames(tempTimeZoneStrings); for iCir := 0 to tempTimeZoneStrings.Count - 1 do begin tempKeyPath := FTimeZoneKeyPath + '\' + tempTimeZoneStrings.Strings[iCir]; tempReg := TRegistry.Create; try tempReg.RootKey := HKEY_LOCAL_MACHINE; tempReg.OpenKey(tempKeyPath, False); tempTimeZone := TTimeZone.Create; tempTimeZone.TimeZoneName := tempTimeZoneStrings.Strings[iCir]; tempTimeZone.Display := tempReg.ReadString('Display'); tempTimeZone.Std := tempReg.ReadString('Std'); tempTimeZone.Dlt := tempReg.ReadString('Dlt'); tempReg.ReadBinaryData('TZI', tempTimeZone.TZI^, SizeOf(TRegTZIInfo)); FTimeZoneList.AddObject(tempTimeZone.Display, tempTimeZone); if FDefaultTimeZone = nil then CheckISDefaultTimeZone(tempTimeZone); finally tempReg.CloseKey; tempReg.Free; end; end; finally tempTimeZoneStrings.Free; end; finally reg.CloseKey; reg.Free; end; end; constructor TTimeZones.Create; begin FTimeZoneKeyPath := '\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Time Zones'; FTimeZoneList := TStringList.Create; FTimeZoneList.Sorted := True; FDefaultTimeZone := nil; CollectTimeZone; end; procedure TTimeZones.DestoryTimeZones; var iCir: Integer; tempTimeZone: TTimeZone; begin for iCir := 0 to FTimeZoneList.Count - 1 do begin tempTimeZone := TTimeZone(FTimeZoneList.Objects[iCir]); tempTimeZone.Free; end; FTimeZoneList.Clear; FTimeZoneList.Free; end; destructor TTimeZones.Destroy; begin DestoryTimeZones(); inherited; end; function TTimeZones.FindTimeZone(const ADisplay: string): TTimeZone; var iIndex: Integer; begin Result := nil; FTimeZoneList.Sort; if FTimeZoneList.Find(ADisplay, iIndex) then begin Result := TTimeZone(FTimeZoneList.Objects[iIndex]); end; end; { TTimeZone } constructor TTimeZone.Create; begin FTZI := GetMemory(SizeOf(TRegTZIInfo)); FillMemory(FTZI, SizeOf(TRegTZIInfo), 0); end; destructor TTimeZone.Destroy; begin FreeMemory(FTZI); inherited; end; function TTimeZone.GetSelfTimeZoneInformation: TTimeZoneInformation; begin GetTimeZoneInformation(Result); Result.Bias := TZI^.Bias; Result.StandardBias := TZI^.StandardBias; Result.StandardDate := TZI^.StandardDate; Result.DaylightBias := TZI^.DaylightBias; Result.DaylightDate := TZI^.DaylightDate; end; function TTimeZone.LocalDateTimeToUTC(const ALocalDateTime: TDateTime; var AUTC: TDateTime): Boolean; var tempLocalToLocal: TDateTime; iMilliSecond: Int64; begin Result := UTCToLocalDateTime(ALocalDateTime, tempLocalToLocal); if Result then begin if tempLocalToLocal > ALocalDateTime then begin iMilliSecond := MilliSecondsBetween(tempLocalToLocal, ALocalDateTime); AUTC := IncMilliSecond(ALocalDateTime, iMilliSecond * -1); end else begin iMilliSecond := MilliSecondsBetween(ALocalDateTime, tempLocalToLocal); AUTC := IncMilliSecond(ALocalDateTime, iMilliSecond); end; Result := True; end; end; function TTimeZone.UTCToLocalDateTime(const AUTC: TDateTime; var ALocalDateTime: TDateTime): Boolean; var TimeZone: TTimeZoneInformation; stUTC, stLC: SYSTEMTIME; begin Result := False; TimeZone := GetSelfTimeZoneInformation; DateTimeToSystemTime(AUTC, stUTC); if SystemTimeToTzSpecificLocalTime(@TimeZone, stUTC, stLC) then begin ALocalDateTime := SystemTimeToDateTime(stLC); Result := True; end; end; end.
LocalDateTime常用方法有: 1. of():根据指定的年、月、日、时、分、秒创建一个LocalDateTime对象。例如,LocalDateTime.of(2023, 3, 5, 10, 20, 30)可以创建一个表示2023年3月5日10:20:30的LocalDateTime对象。 2. now():获取当前的日期和时间LocalDateTime对象。 3. getYear()、getMonth()、getDayOfMonth()等方法:获取LocalDateTime对象中的年、月、日等具体值。 4. plusXXX()、minusXXX()方法:在LocalDateTime对象上进行日期和时间的加减操作。例如,plusDays(1)可以将日期加1天。 5. withXXX()方法:修改LocalDateTime对象中的某个字段的值,返回一个新的LocalDateTime对象。例如,withYear(2024)可以将年份修改为2024年。 6. format()方法:将LocalDateTime对象格式化为指定的字符串。可以使用DateTimeFormatter类来指定日期时间的格式。 7. compareTo()方法:比较两个LocalDateTime对象的大小。 8. isBefore()、isAfter()方法:判断两个LocalDateTime对象的先后顺序。 9. toLocalDate()、toLocalTime()方法:将LocalDateTime对象转换LocalDate对象或LocalTime对象。 这些方法可以帮助我们对日期和时间进行各种操作和处理。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *2* [LocalDateTime常用方法,一文轻松解决掉你的烦恼!](https://blog.csdn.net/m0_69237510/article/details/129981759)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] - *3* [Scala - 时间工具类 LocalDateTime 常用方法整理](https://blog.csdn.net/BIT_666/article/details/130082525)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值