Java8中的LocalDateTime和Date一些时间操作方法

先记录下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();
}

总结

到此这篇关于Java8中的LocalDateTime和Date一些时间操作方法的文章就介绍到这了,更多相关java8 localdateTime和date内容请搜索我们以前的文章或继续浏览下面的相关文章希望大家以后多多支持我们!

(0)

相关推荐

  • mybatis如何使用Java8的日期LocalDate和LocalDateTime详解

    前言 相信大家应该都知道,在实体Entity里面,可以使用java.sql.Date.java.sql.Timestamp.java.util.Date来映射到数据库的date.timestamp.datetime等字段 但是,java.sql.Date.java.sql.Timestamp.java.util.Date这些类都不好用,很多方法都过时了. Java8里面新出来了一些API,LocalDate.LocalTime.LocalDateTime 非常好用 默认的情况下,在mybatis

  • JDBC中使用Java8的日期LocalDate和LocalDateTime操作mysql、postgresql

    前言 相信大家应该都知道,在实体Entity里面,可以使用java.sql.Date.java.sql.Timestamp.java.util.Date来映射到数据库的date.timestamp.datetime等字段 但是,java.sql.Date.java.sql.Timestamp.java.util.Date这些类都不好用,很多方法都过时了. Java8里面新出来了一些API,LocalDate.LocalTime.LocalDateTime 非常好用 如果想要在JDBC中,使用Ja

  • java8 LocalDate LocalDateTime等时间类用法实例分析

    本文实例讲述了java8 LocalDate LocalDateTime等时间类用法.分享给大家供大家参考,具体如下: 这篇文章主要是java8中新的Date和Time API的实战.新的Date和Time类是Java开发者社区千呼万唤始出来的.Java8 之前存在的Date类一直都受人诟病,很多人都会选择使用第三方的date库joda-time.Java8中的date和time api是jodatime的作者参与开发的,实现了JSR310的全部内容.这些新的api都在包java.time下.

  • Java8 LocalDateTime极简时间日期操作小结

    简述 时间日期处理是平时工作中使用非常频繁的逻辑,Java8中提供的新的时间类LocalDateTime和LocalDate,使日期处理可以更简单. 友情提醒下,业务开发中最好默认使用LocalDateTime,因为LocalDateTime可以很方便的转换为LocalDate,但是LocalDate是不可以转为LocalDateTime的,会没有时分秒的数据!!! 本篇文章整理了常用的日期处理获取方式,并做简要说明. 能写一行的,就不写两行!文章会持续更新. 实例 1.获取当前年月日的字符串

  • Java8时间转换(LocalDateTime)代码实例

    这篇文章主要介绍了java8时间转换(LocalDateTime)代码实例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 1.将LocalDateTime转为自定义的时间格式的字符串 public static String getDateTimeAsString(LocalDateTime localDateTime, String format) { DateTimeFormatter formatter = DateTimeFormatt

  • Java8中的LocalDateTime和Date一些时间操作方法

    先记录下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("yyy

  • 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转为t

  • 为何Java8需要引入新的日期与时间库

    1.Date日期输出可读性较差 Date date = new Date(); System.out.println(date); 打印输出的结果: Sat Nov 14 11:03:41 CST 2020 2.Date日期的解析.格式化通过JDK自带的api实现较为麻烦,通常会使用第三方的日期时间库,比如: joda-time , commons-lang Java8中提供了哪些日期和时间类 在java.time包中提供了很多新的类,通常主要使用到的是 LocalDate , LocalTim

  • 如何在Spring Boot应用中优雅的使用Date和LocalDateTime的教程详解

    Java8已经发布很多年了,但是很多人在开发时仍然坚持使用着Date和SimpleDateFormat进行时间操作.SimpleDateFormat不是线程安全的,而Date处理时间很麻烦,所以Java8提供了LocalDateTime.LocalDate和LocalTime等全新的时间操作API.无论是Date还是LocalDate,在开发Spring Boot应用时经常需要在每个实体类的日期字段上加上@DateTimeFormat注解来接收前端传值与日期字段绑定,加上@JsonFormat注

  • Java8中 LocalDate和java.sql.Date的相互转换操作

    一.简述 首先,Java 8引入了java.time.LocalDate来表示一个没有时间的日期. 其次,使用Java 8版本,还需要更新java.sql.Date,以便为LocalDate提供支持,包括toLocalDate和valueOf(LocalDate)等方法. 二.java.time.LocalDate转换为java.sql.Date java.sql.Date.valueOf( localDate ) package insping; public class Test { pub

  • 一篇文章弄懂Java8中的时间处理

    目录 前言 LocalDateTime ZonedDateTime Instant 总结 前言 java8借鉴了第三方日期库joda很多的优点 java.time包 类名 描述 Instant 时间戳 Duration 持续时间,时间差 LocalDate 只包含日期,比如:2020-05-20 LocalTime 只包含时间,比如:13:14:00 LocalDateTime 包含日期和时间,比如:2020-05-20 13:14:00 Period 时间段 ZoneOffset 时区偏移量,

  • Java8新特性Optional类及新时间日期API示例详解

    目录 Optional类 以前对null的处理 Optional类介绍 Optional的基本使用 Optional的常用方法 新时间日期API 旧版日期时间的问题 新日期时间API介绍 日期时间的常见操作 日期时间的修改和比较 格式化和解析操作 Instant类 计算日期时间差 时间校正器 日期时间的时区 JDK新的日期和时间API的优势 Optional类 面试官:Optional类了解过吗? 这个Optional类主要是解决空指针的问题. 以前对null的处理 @Test public v

  • 通过实例解析java8中的parallelStream

    这篇文章主要介绍了通过实例解析java8中的parallelStream,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 about Stream 什么是流? Stream是java8中新增加的一个特性,被java猿统称为流. Stream 不是集合元素,它不是数据结构并不保存数据,它是有关算法和计算的,它更像一个高级版本的 Iterator.原始版本的 Iterator,用户只能显式地一个一个遍历元素并对其执行某些操作:高级版本的 Stream

  • Spring中使用LocalDateTime、LocalDate等参数作为入参

    0x0 背景 项目中使用LocalDateTime系列作为dto中时间的类型,但是spring收到参数后总报错,为了全局配置时间类型转换,尝试了如下3中方法. 注:本文基于Springboot2.0测试,如果无法生效可能是spring版本较低导致的.PS:如果你的Controller中的LocalDate类型的参数啥注解(RequestParam.PathVariable等)都没加,也是会出错的,因为默认情况下,解析这种参数使用ModelAttributeMethodProcessor进行处理,

  • 深入浅出Java8中parallelStream的使用

    about Stream 什么是流? Stream是java8中新增加的一个特性,被java猿统称为流. Stream 不是集合元素,它不是数据结构并不保存数据,它是有关算法和计算的,它更像一个高级版本的 Iterator.原始版本的 Iterator,用户只能显式地一个一个遍历元素并对其执行某些操作:高级版本的 Stream,用户只要给出需要对其包含的元素执行什么操作,比如 "过滤掉长度大于 10 的字符串"."获取每个字符串的首字母"等,Stream 会隐式地在

随机推荐