Java8中的LocalDateTime和Date一些时间操作方法
作者:小小华bk 发布时间:2022-06-28 12:28:57
先记录下jdk8之前的一些帮助方法
判断time是否在now的n天之内
/**
* 判断time是否在now的n天之内
* @param time
* @param now
* @param n 正数表示在条件时间n天之后,负数表示在条件时间n天之前
* @return
*/
public static boolean belongDate(Date time, Date now, int n) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Calendar calendar = Calendar.getInstance(); //得到日历
calendar.setTime(now);//把当前时间赋给日历
calendar.add(Calendar.DAY_OF_MONTH, n);
Date before7days = calendar.getTime(); //得到n前的时间
if (before7days.getTime() < time.getTime()) {
return true;
} else {
return false;
}
}
判断某个时间是否是在条件的起始时间与结束时间之内
/**
* 判断time是否在from,to之内
*
* @param time 指定日期
* @param from 开始日期
* @param to 结束日期
* @return
*/
public static boolean belongCalendar(Date time, Date from, Date to) {
Calendar date = Calendar.getInstance();
date.setTime(time);
Calendar after = Calendar.getInstance();
after.setTime(from);
Calendar before = Calendar.getInstance();
before.setTime(to);
if (date.after(after) && date.before(before)) {
return true;
} else {
return false;
}
}
判断给定时间与当前时间相差多少天
public static long getDistanceDays(String date) {
DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
long days = 0;
try {
Date time = df.parse(date);//String转Date
Date now = new Date();//获取当前时间
long time1 = time.getTime();
long time2 = now.getTime();
long diff = time1 - time2;
days = diff / (1000 * 60 * 60 * 24);
} catch (Exception e) {
e.printStackTrace();
}
return days;//正数表示在当前时间之后,负数表示在当前时间之前
}
将Date转换成String
private static final String LONG_PATTERN="yyyy-MM-dd HH:mm:ss";
private static final String SHORT_PATTERN="yyyy-MM-dd";
/**
* 将日期转换为字符串
*/
public static String parse( Date d, String pattern){
DateFormat df=null;
if( pattern!=null && !"".equals(pattern) ){
df=new SimpleDateFormat(pattern);
}else{
df=new SimpleDateFormat(LONG_PATTERN);
}
return df.format( d );
}
将String转换成Date
private static final String LONG_PATTERN="yyyy-MM-dd HH:mm:ss";
private static final String SHORT_PATTERN="yyyy-MM-dd";
/**
* 将字符串转为日期
*/
public static Date parseStringToDate(String str, String pattern){
DateFormat df = null;
if( pattern!=null && !"".equals(pattern) ){
df=new SimpleDateFormat( pattern );
}else{
df=new SimpleDateFormat( LONG_PATTERN );
}
Date d=null;
try {
d=df.parse(str);
} catch (ParseException e) {
e.printStackTrace();
}
return d;
}
获取指定年后的日期(例如三年后的日期)
Calendar date = Calendar.getInstance();
date.setTime(new Date());
date.add(Calendar.YEAR, +3);
//倒计时结束后的时间
Date scrap_year = date.getTime();
System.out.println("三年后时间" + scrap_year);
Jdk8改革
LocalDateTime获取毫秒数
//获取秒数
Long second = LocalDateTime.now().toEpochSecond(ZoneOffset.of("+8"));
//获取毫秒数
Long milliSecond = LocalDateTime.now().toInstant(ZoneOffset.of("+8")).toEpochMilli();
LocalDateTime与String互转
//时间转字符串格式化
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmssSSS");
String dateTime = LocalDateTime.now(ZoneOffset.of("+8")).format(formatter);
//字符串转时间
String dateTimeStr = "2018-07-28 14:11:15";
DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
LocalDateTime dateTime = LocalDateTime.parse(dateTimeStr, df);Date与LocalDateTime互转
//将java.util.Date 转换为java8 的java.time.LocalDateTime,默认时区为东8区
public static LocalDateTime dateConvertToLocalDateTime(Date date) {
return date.toInstant().atOffset(ZoneOffset.of("+8")).toLocalDateTime();
}
//将java8 的 java.time.LocalDateTime 转换为 java.util.Date,默认时区为东8区
public static Date localDateTimeConvertToDate(LocalDateTime localDateTime) {
return Date.from(localDateTime.toInstant(ZoneOffset.of("+8")));
}
将LocalDateTime转为自定义的时间格式的字符串
public static String getDateTimeAsString(LocalDateTime localDateTime, String format) {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern(format);
return localDateTime.format(formatter);
}
将某时间字符串转为自定义时间格式的LocalDateTime
public static LocalDateTime parseStringToDateTime(String time, String format) {
DateTimeFormatter df = DateTimeFormatter.ofPattern(format);
return LocalDateTime.parse(time, df);
}
将long类型的timestamp转为LocalDateTime
public static LocalDateTime getDateTimeOfTimestamp(long timestamp) {
Instant instant = Instant.ofEpochMilli(timestamp);
ZoneId zone = ZoneId.systemDefault();
return LocalDateTime.ofInstant(instant, zone);
}
将LocalDateTime转为long类型的timestamp
public static long getTimestampOfDateTime(LocalDateTime localDateTime) {
ZoneId zone = ZoneId.systemDefault();
Instant instant = localDateTime.atZone(zone).toInstant();
return instant.toEpochMilli();
}
来源:https://blog.csdn.net/qq_36827957/article/details/90286149
猜你喜欢
- @pathvariable与@requestparam碰到的一些问题一、@pathvariable可以将 URL 中占位符参数绑定到控制器处
- 演示代码如下:package swt_jface.demo11; import org.eclipse.swt.SWT; import or
- idea pom文件图标不对今天遇到一个奇怪的现象,如下图原先pom的图标应该是有个m的,现在直接变成了xml的文件了。右边的Maven P
- 单线程是安全的,因为线程只有一个,不存在多个线程抢夺同一个资源代码例子:public class SingleThread {int num
- java语言里包含了许多对设计模式的直接支持,如command模式,agent模式,observer模式等。虽然java提供的对
- 大致思路:注解实现方式:就是用 反射机制. 获取指定的包下使用了注解的类,存储在一个map容器, 然后获取map容器下类的属性, 利用反射给
- 前言在上一篇文章中讲完了SpringMVC的大部分知识,此篇文章中主要讲解 * 。上一篇文章🚩 * 的使用是非常普遍的。例如在 OA系统中通
- 背景:在Android中按照数据保存的方式,可以分为如下几种Content Provider (用的SQLite实现),SQLite,Sha
- 多线程的创建,方式一:继承于Thread类1.创建一个继承于Thread类的子类2.重写Thread类的run()--->将此线程执行
- 前言当初年少懵懂,那年夏天填志愿选专业,父母听其他长辈说选择计算机专业好。从那以后,我的身上就有了计院深深的烙印。从寝室到机房,从机房到图书
- HTTP请求:如果需要Json格式的自己转下,度娘上N种姿势…//处理http请求 requestUrl为请求地址 requestMetho
- 我们在使用SpringBoot进行测试的时候一般是需要加两个注解:@SpringBootTest目的是加载ApplicationContex
- 前言本文简单介绍抽象类,接口以及它们的异同点,另附简单的代码举例。一、抽象类是什么?在 Java 语言中使用 abstract class
- 我们开发任何一个Spring Boot项目,都会用到如下的启动类@SpringBootApplication public class Ap
- 本文实例为大家分享了OpenCV实现人脸识别程序的具体代码,供大家参考,具体内容如下//Haar特征检测,人脸识别算法,是用xml作为训练后
- springboot开启事务很简单,只需要一个注解@Transactional 就可以了。因为在springboot中已经默认对jpa、jd
- 概念介绍不同的引用类型,主要体现的是对象不同的可达性(reachable)状态和对垃圾收集的影响。01. 强引用这个就
- 这篇文章介绍了Java+Nginx实现POP、IMAP、SMTP邮箱代理服务,我们本次使用的环境为Centos7下,java程序我们通过ec
- 1.将本地jar包放入本地仓库。只需执行如下命令即可:mvn install:install-file -Dfile=D:/demo/fib
- Map集合和Collection集合的区别Map集合是有Key和Value的,Collection集合是只有Value。Collection