Java8中LocalDateTime与时间戳timestamp的互相转换
作者:荒野大码农 发布时间:2023-11-10 05:20:21
标签:java8,localdatetime,timestamp
Java8 LocalDateTime与timestamp转换
将timestamp转为LocalDateTime
public LocalDateTime timestamToDatetime(long timestamp){
Instant instant = Instant.ofEpochMilli(timestamp);
return LocalDateTime.ofInstant(instant, ZoneId.systemDefault());
}
将LocalDataTime转为timestamp
public long datatimeToTimestamp(LocalDateTime ldt){
long timestamp = ldt.toInstant(ZoneOffset.of("+8")).toEpochMilli();
return timestamp;
}
我在网上还找到了另一个将datetime转为时间戳的方法:
ZoneId zone = ZoneId.systemDefault();
long timestamp = ldt.atZone(zone).toInstant().toEpochMilli();
Java8的时间转为时间戳的大概的思路就是LocalDateTime先转为Instant,设置时区,然后转timestamp。
附一个Java8中的LocalDateTime工具类
工具类
package com.kingboy.common.utils.date;
import java.time.*;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.time.temporal.TemporalUnit;
import java.util.Date;
/*
* @author kingboy
* @Date 2017/7/22 下午2:12
* @Description LocalDateTimeUtils is used to Java8中的时间类
*/
public class LocalDateTimeUtils {
//获取当前时间的LocalDateTime对象
//LocalDateTime.now();
//根据年月日构建LocalDateTime
//LocalDateTime.of();
//比较日期先后
//LocalDateTime.now().isBefore(),
//LocalDateTime.now().isAfter(),
//Date转换为LocalDateTime
public static LocalDateTime convertDateToLDT(Date date) {
return LocalDateTime.ofInstant(date.toInstant(), ZoneId.systemDefault());
}
//LocalDateTime转换为Date
public static Date convertLDTToDate(LocalDateTime time) {
return Date.from(time.atZone(ZoneId.systemDefault()).toInstant());
}
//获取指定日期的毫秒
public static Long getMilliByTime(LocalDateTime time) {
return time.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli();
}
//获取指定日期的秒
public static Long getSecondsByTime(LocalDateTime time) {
return time.atZone(ZoneId.systemDefault()).toInstant().getEpochSecond();
}
//获取指定时间的指定格式
public static String formatTime(LocalDateTime time,String pattern) {
return time.format(DateTimeFormatter.ofPattern(pattern));
}
//获取当前时间的指定格式
public static String formatNow(String pattern) {
return formatTime(LocalDateTime.now(), pattern);
}
//日期加上一个数,根据field不同加不同值,field为ChronoUnit.*
public static LocalDateTime plus(LocalDateTime time, long number, TemporalUnit field) {
return time.plus(number, field);
}
//日期减去一个数,根据field不同减不同值,field参数为ChronoUnit.*
public static LocalDateTime minu(LocalDateTime time, long number, TemporalUnit field){
return time.minus(number,field);
}
/**
* 获取两个日期的差 field参数为ChronoUnit.*
* @param startTime
* @param endTime
* @param field 单位(年月日时分秒)
* @return
*/
public static long betweenTwoTime(LocalDateTime startTime, LocalDateTime endTime, ChronoUnit field) {
Period period = Period.between(LocalDate.from(startTime), LocalDate.from(endTime));
if (field == ChronoUnit.YEARS) return period.getYears();
if (field == ChronoUnit.MONTHS) return period.getYears() * 12 + period.getMonths();
return field.between(startTime, endTime);
}
//获取一天的开始时间,2017,7,22 00:00
public static LocalDateTime getDayStart(LocalDateTime time) {
return time.withHour(0)
.withMinute(0)
.withSecond(0)
.withNano(0);
}
//获取一天的结束时间,2017,7,22 23:59:59.999999999
public static LocalDateTime getDayEnd(LocalDateTime time) {
return time.withHour(23)
.withMinute(59)
.withSecond(59)
.withNano(999999999);
}
}
测试类
package com.kingboy.common.localdatetimeutils;
import com.kingboy.common.utils.date.LocalDateTimeUtils;
import org.junit.Test;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import static com.kingboy.common.utils.date.LocalDateTimeUtils.getDayEnd;
import static com.kingboy.common.utils.date.LocalDateTimeUtils.getDayStart;
/**
* @author kingboy
* @Date 2017/7/22 下午7:16
* @Description LocaDateTimeUtilsTest is used to 测试LocalDateTime工具
*/
public class LocaDateTimeUtilsTest {
@Test
public void format_test() {
System.out.println(LocalDateTimeUtils.formatNow("yyyy年MM月dd日 HH:mm:ss"));
}
@Test
public void betweenTwoTime_test() {
LocalDateTime start = LocalDateTime.of(1993, 10, 13, 11, 11);
LocalDateTime end = LocalDateTime.of(1994, 11, 13, 13, 13);
System.out.println("年:" + LocalDateTimeUtils.betweenTwoTime(start, end, ChronoUnit.YEARS));
System.out.println("月:" + LocalDateTimeUtils.betweenTwoTime(start, end, ChronoUnit.MONTHS));
System.out.println("日:" + LocalDateTimeUtils.betweenTwoTime(start, end, ChronoUnit.DAYS));
System.out.println("半日:" + LocalDateTimeUtils.betweenTwoTime(start, end, ChronoUnit.HALF_DAYS));
System.out.println("小时:" + LocalDateTimeUtils.betweenTwoTime(start, end, ChronoUnit.HOURS));
System.out.println("分钟:" + LocalDateTimeUtils.betweenTwoTime(start, end, ChronoUnit.MINUTES));
System.out.println("秒:" + LocalDateTimeUtils.betweenTwoTime(start, end, ChronoUnit.SECONDS));
System.out.println("毫秒:" + LocalDateTimeUtils.betweenTwoTime(start, end, ChronoUnit.MILLIS));
//=============================================================================================
/*
年:1
月:13
日:396
半日:792
小时:9506
分钟:570362
秒:34221720
毫秒:34221720000
*/
}
@Test
public void plus_test() {
//增加二十分钟
System.out.println(LocalDateTimeUtils.formatTime(LocalDateTimeUtils.plus(LocalDateTime.now(),
20,
ChronoUnit.MINUTES), "yyyy年MM月dd日 HH:mm"));
//增加两年
System.out.println(LocalDateTimeUtils.formatTime(LocalDateTimeUtils.plus(LocalDateTime.now(),
2,
ChronoUnit.YEARS), "yyyy年MM月dd日 HH:mm"));
//=============================================================================================
/*
2017年07月22日 22:53
2019年07月22日 22:33
*/
}
@Test
public void dayStart_test() {
System.out.println(getDayStart(LocalDateTime.now()));
System.out.println(getDayEnd(LocalDateTime.now()));
//=============================================================================================
/*
2017-07-22T00:00
2017-07-22T23:59:59.999999999
*/
}
}
总结
来源:https://blog.csdn.net/czx2018/article/details/85005466


猜你喜欢
- 从C#3.0开始,可以使用lambda表达式把实现代码赋予委托。lambda表达式与委托(https://www.jb51.net/arti
- 前言如今发短信功能已经成为互联网公司的标配,本篇文章将一步步实现java发送短信考察了许多提供短信服务的三方,几乎所有都需要企业认证才可以使
- 本文实例讲述了Android互联网访问图片并在客户端显示的方法。分享给大家供大家参考,具体如下:1、布局界面<RelativeLayo
- 1. 背景在业务处理完之后,需要调用其他系统的接口,将相应的处理结果通知给对方,若是同步请求,假如调用的系统出现异常或是宕机等事件,会导致自
- 国家气象局提供了三种数据的形式网址在:http://www.weather.com.cn/data/sk/101010100.htmlhtt
- TransactionTemplate的使用总结:在类中注入TransactionTemplate,即可在springboot中使用编程式事
- 启动App进程Activity启动过程的一环是调用ActivityStackSupervisor.startSpecificActivity
- 最近一段时间生产环境频繁出问题,每次都会生成一个hs_err_pid*.log文件,因为工作内容的原因,在此之前并没有了解过相关内容,趁此机
- nacos升级spring cloud 2020.0无法使用bootstrap.yml之前用spring cloud整合nacos,需要一个
- 如:string str1 = "This is a test";string str2 = "This-is
- 概述spirng-aop模块是Spring框架中的核心模块,虽然Spring Ioc container并不依赖AOP,但AOP给Ioc的实
- 如何检查一个数组(无序)是否包含一个特定的值?这是一个在Java中经常用到的并且非常有用的操作。同时,这个问题在Stack Overflow
- Lambda 表达式Lambda 表达式是现代 C++ 中最重要的特性之一,而 Lambda 表达式,实际上就是提供了一个类似匿名函数的特性
- 本文实例讲述了Java判断两个日期相差天数的方法。分享给大家供大家参考。具体如下:import java.util.Calendar;pub
- 最近有一款2048的游戏非常火,本文将来介绍一下使用OGEngine游戏引擎开发游戏2048。OGEngine引擎是开源的,我们很容易找到,
- 今天整理之前的代码,忽然看到之前自己写的一个刮刮卡,整理下以便以后使用,同时分享给需要的朋友,如有错误,还请多多指正。实现的步骤,其实就是徒
- 编译常见问题在开发过程中,有碰到过一些由于编译优化导致的代码修改并不符合我们预期的情况。这也就是之前为什么我经常说编译产物其实是不太可以被信
- 本文介绍了详解WMI RPC 服务器不可用的解决方案,分享给大家,具体如下:ConnectionOptions connectionOpti
- 众所周知,android的底部菜单栏太重要,平时项目一般都是需要用到的,但是网上关于这方面的demo做得太丑了,实在惨不忍睹,所以这里便用R
- 工厂模式工厂模式顾名思义就是生产实例的工厂,使用工厂模式不会在程序中使用new关键字创建实例。而是将创建对象的细节隐藏,对外提供统一的方法,