Java中关于时间的处理

1.将Long转化成LocalDateTime

	/**
	 * 将Long转化成LocalDateTime
	 * @param time	Long类型的时间戳
	 * @return		LocalDateTime类型的时间
	 */
	public LocalDateTime toLocalDateTime(long time) {
		Instant instant = Instant.ofEpochMilli(time);
		ZoneId zone = ZoneId.systemDefault(); //设置时区
		return LocalDateTime.ofInstant(instant, zone);
	}

2.将LocalDateTime转化成Long

	/**
	 * 将LocalDateTime转化成Long
	 * @param time		LocalDateTime类型的时间
	 * @return 			Long类型的时间戳
	 */
	public Long toLong(LocalDateTime time) {
		ZoneId zone = ZoneId.systemDefault();
		Instant instant = time.atZone(zone).toInstant();
		return instant.toEpochMilli();
		
		//这两种方式都可以,但只要返回一个就可以
		return time.toInstant(ZoneOffset.of("+8")).toEpochMilli();
	}

3.将Date转换成LocalDateTime

	/**
	 * 将Date转换成LocalDateTime
	 * @param date	Date类型的时间
	 * @return		LocalDateTime类型的时间
	 */
	public LocalDateTime toLocalDateTime(Date date) {
		Instant instant = date.toInstant();
		ZoneId zone = ZoneId.systemDefault();
		return LocalDateTime.ofInstant(instant, zone);
	}

4.将LocalDateTime转为自定义的时间格式的字符串

yyyy-MM-dd hh:mm:ss ->年-月-日 时:分:秒
	/**
	 * 将LocalDateTime转为自定义的时间格式的字符串
	 * @param dateTime
	 * @param format
	 * @return
	 */
	public String getLocalDateTimeString(LocalDateTime dateTime, String format) {
	    DateTimeFormatter formatter = DateTimeFormatter.ofPattern(format);
	    return dateTime.format(formatter);
	}

5.将某时间字符串转为自定义时间格式的LocalDateTime

   yyyy-MM-dd hh:mm:ss ->年-月-日 时:分:秒
	/**
	 * 将LocalDateTime转为自定义的时间格式的字符串
	 * @param dateTime
	 * @param format
	 * @return
	 */
	public String getLocalDateTimeString(LocalDateTime dateTime, String format) {
	    DateTimeFormatter formatter = DateTimeFormatter.ofPattern(format);
	    return dateTime.format(formatter);
	}

6.给出一个时间戳,返回该时间所在日期凌晨的时间戳

	/**
	 * 给出一个时间戳,返回该时间所在日期的凌晨时间戳
	 * @param date
	 * @return
	 */
	public Long getTodayZero(Long date) {
		Instant instant = Instant.ofEpochMilli(date);
		ZoneId zone = ZoneId.systemDefault();	//设置时区
		LocalDateTime localDateTime = LocalDateTime.ofInstant(instant, zone);
		LocalDate today = localDateTime.toLocalDate();
		return LocalDateTime.of(today, LocalTime.MIN).toInstant(ZoneOffset.of("+8")).toEpochMilli();
	}

7.给出一个时间戳,返回该时间所在日期的次日凌晨的时间戳

	/**
	 * 给出一个时间戳,返回该时间所在日期的次日凌晨的时间戳
	 * @param date
	 * @return
	 */
	public Long getTomorrowZero(Long date) {
		Instant instant = Instant.ofEpochMilli(date);
		ZoneId zone = ZoneId.systemDefault();	//设置时区
		LocalDateTime localDateTime = LocalDateTime.ofInstant(instant, zone);
		LocalDate today = localDateTime.toLocalDate();
		return LocalDateTime.of(today.plusDays(1), LocalTime.MIN).toInstant(ZoneOffset.of("+8")).toEpochMilli();
	}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

yelvens

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值