来源:https://blog.csdn.net/zhangzijiejiayou/article/details/76597329

LocalDateTime 本地日期时间

LocalDateTime 同时表示了时间和日期,相当于前两节内容合并到一个对象上了。LocalDateTime和LocalTime还有LocalDate一样,都是不可变的。LocalDateTime提供了一些能访问具体字段的方法。
代码如下: LocalDateTime sylvester = LocalDateTime.of(, Month.DECEMBER, , , , ); DayOfWeek dayOfWeek = sylvester.getDayOfWeek();
System.out.println(dayOfWeek); // WEDNESDAY Month month = sylvester.getMonth();
System.out.println(month); // DECEMBER long minuteOfDay = sylvester.getLong(ChronoField.MINUTE_OF_DAY);
System.out.println(minuteOfDay); // 只要附加上时区信息,就可以将其转换为一个时间点Instant对象,Instant时间点对象可以很容易的转换为老式的java.util.Date。代码如下: Instant instant = sylvester
.atZone(ZoneId.systemDefault())
.toInstant(); Date legacyDate = Date.from(instant);
System.out.println(legacyDate); // Wed Dec 31 23:59:59 CET 2014 格式化LocalDateTime和格式化时间和日期一样的,除了使用预定义好的格式外,我们也可以自己定义格式:
代码如下: DateTimeFormatter formatter =
DateTimeFormatter
.ofPattern("MMM dd, yyyy - HH:mm"); LocalDateTime parsed = LocalDateTime.parse("Nov 03, 2014 - 07:13", formatter);
String string = formatter.format(parsed);
System.out.println(string); // Nov 03, 2014 - 07:13 和java.text.NumberFormat不一样的是新版的DateTimeFormatter是不可变的,所以它是线程安全的。 项目中计算两个日期之间的天数代码: LocalDate date1 = LocalDate.parse("2015-12-01");
LocalDate date2 = LocalDate.parse("2016-12-01");
System.out.println(date1.until(date2, ChronoUnit.DAYS)); util包下有各种返回的类型。
private static final ConcurrentMap<String, DateTimeFormatter> FORMATTER_CACHE = new ConcurrentHashMap<>();

    private static final int PATTERN_CACHE_SIZE = ;
/**
* Date转换为格式化时间
* @param date date
* @param pattern 格式
* @return
*/
public static String format(Date date, String pattern){
return format(LocalDateTime.ofInstant(date.toInstant(), ZoneId.systemDefault()), pattern);
} /**
* localDateTime转换为格式化时间
* @param localDateTime localDateTime
* @param pattern 格式
* @return
*/
public static String format(LocalDateTime localDateTime, String pattern){
DateTimeFormatter formatter = createCacheFormatter(pattern);
return localDateTime.format(formatter);
} /**
* 格式化字符串转为Date
* @param time 格式化时间
* @param pattern 格式
* @return
*/
public static Date parseDate(String time, String pattern){
return Date.from(parseLocalDateTime(time, pattern).atZone(ZoneId.systemDefault()).toInstant()); } /**
* 格式化字符串转为LocalDateTime
* @param time 格式化时间
* @param pattern 格式
* @return
*/
public static LocalDateTime parseLocalDateTime(String time, String pattern){
DateTimeFormatter formatter = createCacheFormatter(pattern);
return LocalDateTime.parse(time, formatter);
} /**
* 在缓存中创建DateTimeFormatter
* @param pattern 格式
* @return
*/
private static DateTimeFormatter createCacheFormatter(String pattern){
if (pattern == null || pattern.length() == ) {
throw new IllegalArgumentException("Invalid pattern specification");
}
DateTimeFormatter formatter = FORMATTER_CACHE.get(pattern);
if(formatter == null){
if(FORMATTER_CACHE.size() < PATTERN_CACHE_SIZE){
formatter = DateTimeFormatter.ofPattern(pattern);
DateTimeFormatter oldFormatter = FORMATTER_CACHE.putIfAbsent(pattern, formatter);
if(oldFormatter != null){
formatter = oldFormatter;
}
}
} return formatter;
}
<code class="language-java">/**
* TestLocalDateTime.java
* com.javabase.test17
* 本文转载自 尚硅谷视频中教学代码 http://www.gulixueyuan.com/my/course/56 第十八 十九讲
*/ package com.javabase.test17; import java.time.DayOfWeek;
import java.time.Duration;
import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.OffsetDateTime;
import java.time.Period;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalAdjusters;
import java.util.Set; import org.junit.Test; /**
* java 8 对于日期和时间的使用
*
* @author Chufanzgheng(1280251739@qq.com)
* @Date 2018年1月24日
*/
public class TestLocalDateTime { /**
* localDate The operation of time
*/
@Test
public void test1(){ LocalDateTime localDateTime = LocalDateTime.now();
System.out.print("++++【localDateTime】++++"+localDateTime);
// -------iso 标准时间体系-------
LocalDateTime localDateTime1 = LocalDateTime.of(, , , , );
System.out.println("++++++【localDateTime1】+++++"+localDateTime1);
LocalDateTime localDateTime2 = localDateTime1.minusDays();
System.out.println("+++++++【localDateTime2】+++++++"+localDateTime2);
System.out.println("+++++++【localDateTime2.plusMonths(2)】+++++++++"+localDateTime2.plusMonths());
System.out.println("localDateTime2.getYear()"+localDateTime2.getYear());
System.out.println("localDateTime2.getMonthValue()"+localDateTime2.getMonthValue());
System.out.println("localDateTime2.getMonth()"+localDateTime2.getMonth());
System.out.println("localDateTime2.getDayOfWeek()"+localDateTime2.getDayOfWeek());
System.out.println("localDateTime2.getDayOfMonth()"+localDateTime2.getDayOfMonth());
System.out.println("localDateTime2.getHour()"+localDateTime2.getHour());
System.out.println("localDateTime2.getMinute()"+localDateTime2.getMinute());
System.out.println("localDateTime2.getSecond()"+localDateTime2.getSecond());
} //2. Instant : 时间戳。 (使用 Unix 元年 1970年1月1日 00:00:00 所经历的毫秒值)
@Test
public void test2(){ Instant ins = Instant.now(); //默认使用 UTC 时区
System.out.println(ins);
//偏移时区调整
OffsetDateTime odt = ins.atOffset(ZoneOffset.ofHours()); // 时间偏移量8个小时
System.out.println(odt);
System.out.println("++++ins.getNano()++++"+ins.getNano());
Instant ins2 = Instant.ofEpochSecond();
System.out.println("++++ins2++++"+ins2);
} /**
* 计算时间间隔 Duration Period
* @throws InterruptedException
* toMillis()
*
*/
@Test
public void test3() throws InterruptedException{ Instant instantBegin = Instant.now();
Thread.sleep();
Instant instantEnd = Instant.now();
System.out.println("输出当前时间间隔差"+Duration.between(instantBegin, instantEnd).toMillis());
// -----------------------------------------------------------------------
LocalDate local1 = LocalDate.now();
LocalDate local2 = LocalDate.of(, , );
Period period = Period.between(local1, local2);
System.out.println("++++year++++"+period.getYears());
System.out.println("++++month++++"+period.getMonths());
System.out.println("++++days++++"+period.getDays());
} /**
* 时间校正器
* TemporalAdjuster
*/
@Test
public void test4(){ LocalDateTime ldt = LocalDateTime.now();
System.out.println("-----ldt-----"+ldt); LocalDateTime ldt2 = ldt.withDayOfMonth();//表示为本月中的第几天
System.out.println("----ldt2----"+ldt2); //计算下周一的时间
LocalDateTime ldt3 = ldt.with(TemporalAdjusters.next(DayOfWeek.MONDAY));
System.out.println("------ldt3-----"+ldt3); //自定义:下一个工作日
LocalDateTime ldt4 = ldt.with((local) ->{ LocalDateTime ldt5 = (LocalDateTime) local;
DayOfWeek dow = ldt5.getDayOfWeek(); if(dow.equals(DayOfWeek.FRIDAY)){
return ldt5.plusDays();
}else if(dow.equals(DayOfWeek.SATURDAY)){
return ldt5.plusDays();
}else{
return ldt5.plusDays();
}
});
System.out.println("-------ldt4-----"+ldt4); } /**
* 5. DateTimeFormatter : 解析和格式化日期或时间
*/
@Test
public void test5(){ DateTimeFormatter dateTimeFormater = DateTimeFormatter.ofPattern("yyyy年MM月dd日 HH时mm分ss秒");
LocalDateTime localDateTime = LocalDateTime.now();
System.out.println("【----未格式化之前----】" + localDateTime);
System.out.println("【----格式化之后----】"+dateTimeFormater.format(localDateTime));
} @Test
public void test6(){ Set<String> set = ZoneId.getAvailableZoneIds();
set.forEach(System.out::println);
} /**
* 7.ZonedDate、ZonedTime、ZonedDateTime : 带时区的时间或日期
*/
@Test
public void test7(){ LocalDateTime ldt = LocalDateTime.now(ZoneId.of("Asia/Shanghai"));
System.out.println("----【ldt】----"+ldt); ZonedDateTime zdt = ZonedDateTime.now(ZoneId.of("America/New_York"));
System.out.println("----【zdt】----"+zdt);
} /**
* <B>备注:<B>
*
* zone 英[zəʊn]美[zoʊn]n.地带; 区域,范围; 地区,时区; [物] 晶带;vt. 划分成带; 用带子围绕;vi. 分成区,分成地带;
*
* available 英[əˈveɪləbl]美[əˈveləbəl]adj. 可获得的; 有空的; 可购得的; 能找到的;
*
* offset 美[ˈɔ:fset]vt. 抵消; 补偿; (为了比较的目的而)把…并列(或并置) ;
* 为(管道等)装支管;vi. 形成分支,长出分枝; 装支管;n. 开端; 出发; 平版印刷; 抵消,补偿;
*
* duration 美[duˈreɪʃn] n. 持续,持续的时间,期间; (时间的) 持续,持久,连续; [语音学] 音长,音延;
*
* instant 英[ˈɪnstənt] 美[ˈɪnstənt] n. 瞬间,顷刻; 此刻; 当月; 速食食品,即溶饮料; adj. 立即的; 迫切的; 正在考虑的,目前的; 即食的;
*
* temporal 英[ˈtempərəl] 美[ˈtɛmpərəl,ˈtɛmprəl] adj.时间的; 世俗的; 暂存的; <语>表示时间的; n.暂存的事物,世间的事物; 世俗的权力; 一时的事物,俗事;
*
* adjuster 英[ə'dʒʌstə] 美[ə'dʒʌstə] n.调停者,调节器;
*
*/ } </code>

待整理:

dataUtils:

package com.icil.esolution;

import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date; import org.junit.Test;
import org.springframework.util.Assert; public class DateUtils { /**
* 将字符串转日期成Long类型的时间戳,格式为:yyyy-MM-dd HH:mm:ss
*/
public static Long convertTimeToLong(String timestr) {
Assert.notNull(timestr, "time is null");
DateTimeFormatter ftf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
LocalDateTime parse = LocalDateTime.parse(timestr, ftf);
return LocalDateTime.from(parse).atZone(ZoneId.systemDefault()).toInstant().toEpochMilli();
} /**
* 将Long类型的时间戳转换成String 类型的时间格式,时间格式为:yyyy-MM-dd HH:mm:ss
*/
public static String convertTimeToString(Long time){
Assert.notNull(time, "time is null");
DateTimeFormatter ftf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
return ftf.format(LocalDateTime.ofInstant(Instant.ofEpochMilli(time),ZoneId.systemDefault()));
} @Test
public void testName11() throws Exception {
long time=1417792627L; Assert.notNull(time, "time is null");
DateTimeFormatter ftf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
String format = ftf.format(LocalDateTime.ofInstant(Instant.ofEpochMilli(time),ZoneId.systemDefault()));
System.out.println(format);
} @Test
public void testName() throws Exception {
DateTimeFormatter ftf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
Date date = new Date();
LocalDateTime parse = LocalDateTime.parse("2018-05-29 13:52:50", ftf);
long epochMilli = LocalDateTime.from(parse).atZone(ZoneId.systemDefault()).toInstant().toEpochMilli();
System.out.println(epochMilli);
} /**
* 将Date转换为LocalDatetime,方式:
* @param args
*/
public static LocalDateTime dateToLocalDateTime(Date date) {
// 1.从日期获取ZonedDateTime并使用其方法toLocalDateTime()获取LocalDateTime
// 2.使用LocalDateTime的Instant()工厂方法
Instant instant = date.toInstant();
ZoneId zoneId = ZoneId.systemDefault();
LocalDateTime localDateTime = instant.atZone(zoneId).toLocalDateTime();
return localDateTime;
} /**
* 将LocalDateTime转换回java.util.Date:
* 1.使用atZone()方法将LocalDateTime转换为ZonedDateTime
2.将ZonedDateTime转换为Instant,并从中获取Date
* @param args
*/
public static Date localDateTimeToDate(LocalDateTime localDateTime) {
ZoneId zoneId = ZoneId.systemDefault();
// LocalDateTime localDateTime = LocalDateTime.now();
ZonedDateTime zdt = localDateTime.atZone(zoneId);
Date date = Date.from(zdt.toInstant());
return date;
} @Test
public void testName2() throws Exception {
DateTimeFormatter f = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
//时间转为字符串
LocalDateTime date =LocalDateTime.now();
System.out.println(date);
String str = date.format(f); // 2014-11-07 14:10:36
System.out.println(str);
//字符串转为时间
date = LocalDateTime.parse(str,f);
System.out.println(date);
} }

JDK8时间格式转换的更多相关文章

  1. SQL Server日期时间格式转换字符串详解 (详询请加qq:2085920154)

    在SQL Server数据库中,SQL Server日期时间格式转换字符串可以改变SQL Server日期和时间的格式,是每个SQL数据库用户都应该掌握的.本文我们主要就介绍一下SQL Server日 ...

  2. SQL Server日期时间格式转换字符串

    在SQL Server数据库中,SQL Server日期时间格式转换字符串可以改变SQL Server日期和时间的格式,是每个SQL数据库用户都应该掌握的.本文我们主要就介绍一下SQL Server日 ...

  3. MySQL时间戳和时间格式转换函数

    MySQL时间戳和时间格式转换函数:unix_timestamp and from_unixtime unix_timestamp将时间转化成时间戳格式.from_unixtime将时间戳转化成时间格 ...

  4. Sql日期时间格式转换;取年 月 日,函数:DateName()、DATEPART()

    一.sql server2000中使用convert来取得datetime数据类型样式(全) 日期数据格式的处理,两个示例: CONVERT(varchar(16), 时间一, 20) 结果:2007 ...

  5. SQL Server日期时间格式转换字符串详解

    本文我们主要介绍了SQL Server日期时间格式转换字符串的相关知识,并给出了大量实例对其各个参数进行对比说明,希望能够对您有所帮助. 在SQL Server数据库中,SQL Server日期时间格 ...

  6. sql 日期时间格式转换

    Sql日期时间格式转换   sql server2000中使用convert来取得datetime数据类型样式(全) 日期数据格式的处理,两个示例: CONVERT(varchar(16), 时间一, ...

  7. [php基础]Mysql日期函数:日期时间格式转换函数详解

    在PHP网站开发中,Mysql数据库设计中日期时间字段必不可少,由于Mysql日期函数输出的日期格式与PHP日期函数之间的日期格式兼容性不够,这就需要根据网站实际情况使用Mysql或PHP日期转换函数 ...

  8. lua 特殊时间格式转换

    [1]时间格式转换需求 工作中,因业务需要将时间格式进行转换.需求内容如下: 原格式:17:04:49.475  UTC Mon Mar 04 2019 转换格式:2019-03-04 17:04:4 ...

  9. scala 时间格式转换(String、Long、Date)

    1)scala 时间格式转换(String.Long.Date) 1.时间字符类型转Date类型 [java] view plain copy import java.text.SimpleDateF ...

随机推荐

  1. jspf、jsp小记

    jsp页面:

  2. GVIM设置背景颜色

    首先找到GVim的安装目录,在安装目录下你可以发现一个_vimrc文件,使用文本编辑器打开后在里面添加两行代码即可:代码如下set gfn=Courier_New:h14colorscheme tor ...

  3. jquery3.1.1报错Uncaught TypeError: a.indexOf is not a function

    jquery3.1.1报错Uncaught TypeError: a.indexOf is not a function 使用1.9就没有问题,解决办法: 就是把写的代码中: $(window).lo ...

  4. 三十分钟理解:双调排序Bitonic Sort,适合并行计算的排序算法

    欢迎转载,转载请注明:本文出自Bin的专栏blog.csdn.net/xbinworld 技术交流QQ群:433250724,欢迎对算法.技术.应用感兴趣的同学加入 双调排序是data-indepen ...

  5. Eclipse中使用Maven,报错“$MAVEN_HOME”

    1.今天在用eclipse时,执行maven命令,报错,如图"$MAVEN_HOME" 解决方案: 1.点击 windows---preferences,打开preferences ...

  6. 【C++基础】sort函数

    sort函数的时间复杂度为O(n*logn),排序方法类似于快排. # 头文件 #include<algorithm> using namespace std; # 参数 第一个参数:要排 ...

  7. [笔记]CodeIgniter的SESSION

         由于HTTP协议本身是无状态的,所以当保留某个用户的访问状态信息时,需要客户端有一个唯一标识传给服务端,这个唯一标识就是SESSION ID,存放在客户端的COOKIE中,然后服务端根据该标 ...

  8. Hibernate环境搭建+struts整合

    说明:本文档,是和struts2+hibernate的整合示例. lib下还有struts2的jar包,本示例没有显示.struts2的搭建参考struts2的环境搭建 一下载hibernate的ja ...

  9. QLoo graphql engine 学习一 基本试用(docker&&docker-compose)

      说明:使用docker-compose 进行安装 代码框架 使用命令行工具创建 qlooctl install docker qloo-docker 运行qloo&&gloo 启动 ...

  10. 有些文件不需要配置,只需要放到resources下面

    今天和一位同事探讨了一个问题,开始的时候我事先的读取某个映射文件是配置在applicationContext.xml的bean定义里面:但是他提出来,是否可以不需要配置呢?直接作为一个资源文件完事,这 ...