yyyy-MM-dd -> LocalDateTime

直接把yyyy-MM-dd格式的日期字符串解析成LocalDateTime会抛出异常

  try {
LocalDateTime localDateTime = LocalDateTime.parse("2019-05-27", DateTimeFormatter.ofPattern("yyyy-MM-dd"));
System.out.println(localDateTime);
} catch (Exception ex) {
ex.printStackTrace();
}

抛出如下异常

java.time.format.DateTimeParseException: Text '2019-05-27' could not be parsed: Unable to obtain LocalDateTime from TemporalAccessor: {},ISO resolved to 2019-05-27 of type java.time.format.Parsed
at java.time.format.DateTimeFormatter.createError(DateTimeFormatter.java:1919)
at java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1854)
at java.time.LocalDateTime.parse(LocalDateTime.java:492)
at com.ahut.common.utils.DateTest.testLocalDate(DateTest.java:28)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:483)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47)
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)
Caused by: java.time.DateTimeException: Unable to obtain LocalDateTime from TemporalAccessor: {},ISO resolved to 2019-05-27 of type java.time.format.Parsed
at java.time.LocalDateTime.from(LocalDateTime.java:461)
at java.time.LocalDateTime$$Lambda$7/762152757.queryFrom(Unknown Source)
at java.time.format.Parsed.query(Parsed.java:226)
at java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1850)
... 24 more
Caused by: java.time.DateTimeException: Unable to obtain LocalTime from TemporalAccessor: {},ISO resolved to 2019-05-27 of type java.time.format.Parsed
at java.time.LocalTime.from(LocalTime.java:409)
at java.time.LocalDateTime.from(LocalDateTime.java:457)
... 27 more

解决办法yyyy-MM-dd -> LocalDate -> LocalDateTime

 try {
LocalDate localDate = LocalDate.parse("2019-05-27", DateTimeFormatter.ofPattern("yyyy-MM-dd"));
LocalDateTime localDateTime = localDate.atStartOfDay();
System.out.println(localDateTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
} catch (Exception ex) {
ex.printStackTrace();
}

输出

2019-05-27 00:00:00

LocalDate atStartOfDay方法源码

    /**
* Combines this date with the time of midnight to create a {@code LocalDateTime}
* at the start of this date.
* <p>
* This returns a {@code LocalDateTime} formed from this date at the time of
* midnight, 00:00, at the start of this date.
*
* @return the local date-time of midnight at the start of this date, not null
*/
public LocalDateTime atStartOfDay() {
return LocalDateTime.of(this, LocalTime.MIDNIGHT);
}

LocalTime常量

  /**
* The minimum supported {@code LocalTime}, '00:00'.
* This is the time of midnight at the start of the day.
*/
public static final LocalTime MIN;
/**
* The maximum supported {@code LocalTime}, '23:59:59.999999999'.
* This is the time just before midnight at the end of the day.
*/
public static final LocalTime MAX;
/**
* The time of midnight at the start of the day, '00:00'.
*/
public static final LocalTime MIDNIGHT;
/**
* The time of noon in the middle of the day, '12:00'.
*/
public static final LocalTime NOON;
/**
* Constants for the local time of each hour.
*/
private static final LocalTime[] HOURS = new LocalTime[24];

扩展

获取当前日期最早时间和最晚时间

 System.out.println(LocalDateTime.of(LocalDate.now(), LocalTime.MIN).format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
System.out.println(LocalDateTime.of(LocalDate.now(), LocalTime.MAX).format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
2019-05-27 00:00:00
2019-05-27 23:59:59

封装解析方法

 /**
* desc :
* create_user : cheng
* create_date : 2019/5/27 19:28
*/
private LocalDateTime parseToLocalDateTime(String str, String pattern) {
if (StringUtils.isAnyBlank(str, pattern)) {
return null;
} LocalDateTime localDateTime;
try {
localDateTime = LocalDateTime.parse(str, DateTimeFormatter.ofPattern(pattern));
} catch (Exception ex) {
ex.printStackTrace();
LocalDate localDate = parseLocalDate(str, pattern);
localDateTime = Objects.isNull(localDate) ? null : localDate.atStartOfDay();
}
return localDateTime;
} /**
* desc :
* create_user : cheng
* create_date : 2019/5/27 19:30
*/
private LocalDate parseLocalDate(String str, String pattern) {
if (StringUtils.isAnyBlank(str, pattern)) {
return null;
} LocalDate localDate = null;
try {
localDate = LocalDate.parse(str, DateTimeFormatter.ofPattern(pattern));
} catch (Exception ex) {
ex.printStackTrace();
}
return localDate;
}

调用

  System.out.println("解析: " + parseToLocalDateTime("2019-05-27", "yyyy-MM-dd")
.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));

结果

解析: 2019-05-27 00:00:00

关于yyyy-MM-dd格式日期字符串,解析成LocalDateTime遇到的问题的更多相关文章

  1. Excel日期格式单元格写成yyyy.MM.dd格式将无法读取到DataTable

    最近在改公司的订单系统,遇到了一个奇怪的问题.C#程序需要从Excel文件中将数据全部读取到DataTable,其中Excel文件的第一列是日期格式yyyy/MM/dd,而这一列中大部分的单元格都是按 ...

  2. 数据库中取出YYYY-mm-dd H:i:s的数据怎么将其转化成YYYY/mm/dd格式,另外,怎么将一个数据表中的数据插入另一个数据表

    sql语句是select  left(replace(rq,'-','/'),10) as rq from 表名 tp5.1中的写法 $res = Db::table('表名') ->field ...

  3. JS中如何将yyyy-MM-dd HH:mm:ss格式的字符串转成Date类型

    var deadline = '2019-04-11 13:11:00';   var result = new Date(deadline.replace(/-/g, '/'));

  4. Java8获取当前时间、新的时间日期类如Java8的LocalDate与Date相互转换、ZonedDateTime等常用操作包含多个使用示例、Java8时区ZoneId的使用方法、Java8时间字符串解析成类

     下面将依次介绍 Date转Java8时间类操作 ,Java8时间类LocalDate常用操作(如获得当前日期,两个日期相差多少天,下个星期的日期,下个月第一天等) 解析不同时间字符串成对应的Java ...

  5. 让用户输入一个日期字符串,将其转换成日期格式, 格式是(yyyy/MM/dd,yyyyMMdd,yyyy-MM-dd)中的一种, 任何一种转换成功都可以; 如果所有的都无法转换,输出日期格式非法。

    第三种方法 while(true) {             Date d;        System.out.println("正在进行第一次匹配,请稍后~—~");     ...

  6. C# 时间格式 yyyy/mm/dd

    今天遇到个问题在C#中将日期格式设置为yyyy/MM/dd,我是这样写的: DateTime.Now.ToString("yyyy/MM/dd"); 可是获取到的日期还是显示yyy ...

  7. Oracle中把一个DateTime的字符串转化成date类型。to_date('2016/12/8 18:55:43','yyyy/MM/dd hh24:mi:ss'),

    Oracle中把一个DateTime或者该形态字符串转化成date类型. to_date('2016/12/8 18:55:43','yyyy/MM/dd hh24:mi:ss'), 或者: sele ...

  8. 日期字符串解析--SimpleDateFormat严格限制日期转换setLenient(false)

    输入“33/12/2011”,用SimpleDateFormat parse()方法,转化为Date(2012,01,02).这样处理相当“33/12/2011”是正常输入,如果需要"33/ ...

  9. DateTime.Now.ToString("yyyy/MM/dd") 输出的结果是 2006-03-16(转)

    今天我在使用 DateTime.Now.ToString("yyyy/MM/dd") 输出的结果是 2006-03-16 而不是我想要的 2006/03/16,都快把我郁闷的不行了 ...

随机推荐

  1. leetcode——动态规划

    立志要熟练动态规划,加油! 最长回文子串给定一个字符串 s,找到 s 中最长的回文子串.你可以假设 s 的最大长度为 1000. 思路:设dp[l][r]表示s[l……r]是否回文,枚举右边界r,然后 ...

  2. 【tf.keras】tf.keras使用tensorflow中定义的optimizer

    Update:2019/09/21 使用 tf.keras 时,请使用 tf.keras.optimizers 里面的优化器,不要使用 tf.train 里面的优化器,不然学习率衰减会出现问题. 使用 ...

  3. shiro授权、注解式开发

    在ShiroUserMapper.xml中新增内容 <select id="getRolesByUserId" resultType="java.lang.Stri ...

  4. 201871010102-常龙龙《面向对象程序设计(java)》第一周学习总结

    博文正文开头:(3分) 项目 内容 这个作业属于哪个课程 https://www.cnblogs.com/nwnu-daizh/p/11435127.html 这个作业的要求在哪里 https://e ...

  5. WPF 精修篇 page

    原文:WPF 精修篇 page 前言 前段时间看UML 大象 这本书 虽然马上看到了精华片 最后还是暂时暂停 因为这本书 很好 但是暂时对现在的我来说 有点超前 很多东西理解起来还是很难 但是 这本书 ...

  6. 新工具解决消息丢失的bug

    最近在调查一个消息丢失的bug,所幸客户的文本文件里有丢失的记录,但在localdb文件里找不到. 我当时的想法是,在运行report的时候把丢失的记录从文本文件找出来,然后添加到localdb里,最 ...

  7. 用VB脚本复制文件夹并跳过重复文件

    VB中可通过 scripting.filesystemobject 对象操作文件,其中复制文件或文件夹的函数参数可选覆盖或不覆盖.选择覆盖时,如果目标路径存在同名文件或文件夹,则替换掉已存在的文件.而 ...

  8. celery生产者-消费者

    Celery是一个简单,灵活,可靠的分布式系统,用于处理大量消息,同时为操作提供维护此类系统所需的工具. 它是一个任务队列,专注于实时处理,同时还支持任务调度. celery解决了什么问题: 示例一: ...

  9. 使用Runtime的objc_msgSend实现模型和字典的互转

    一.介绍 模型转字典,字典转模型,这是开发中最基本的功能.系统类中提供了一个setValuesForKeysWithDictionary方法来实现字典转模型,至于模型转字典,这个就需要使用runtim ...

  10. app自动化测试环境搭建之node+appium+ADT+MUMU模拟器

    一.安装Microsoft .NET Framework 4.5 检测本机已安装的程序中,是否已经安装Microsoft .NET Framework 4.5及以上的版本 如果没有安装,则获取安装文件 ...