Java 8添加了一个新的java.time API来处理日期和时间(JSR 310).
我有日期和时间作为字符串(例如"2014-04-08 12:30").如何LocalDateTime从给定的字符串中获取实例?
在我完成LocalDateTime对象的使用之后:如何将LocalDateTime实例转换回具有与上面所示格式相同的字符串?
随着Mac OS X(Mavericks)上的第一个Java 8(b132)发布,使用新的java.time包的代码可以工作:
String input = "20111203123456";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern( "yyyyMMddHHmmss");
LocalDateTime localDateTime = LocalDateTime.parse( input, formatter );
Run Code Online (Sandbox Code Playgroud)
渲染:
2011-12-03T12:34:56
Run Code Online (Sandbox Code Playgroud)
但是当我按照DateTimeFormatter类doc中的指定添加"SS"作为秒的小数(和"55"作为输入)时,会抛出异常:
java.time.format.DateTimeParseException: Text '2011120312345655' could not be parsed at index 0
Run Code Online (Sandbox Code Playgroud)
该文档说默认使用严格模式,并且需要与输入数字相同数量的格式字符.所以我很困惑为什么这段代码失败了:
String input = "2011120312345655";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern( "yyyyMMddHHmmssSS");
LocalDateTime localDateTime = LocalDateTime.parse( input, formatter );
Run Code Online (Sandbox Code Playgroud)
使用文档中的示例("978")的另一个示例(失败):
String input = "20111203123456978";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern( "yyyyMMddHHmmssSSS");
LocalDateTime localDateTime = LocalDateTime.parse( input, formatter );
Run Code Online (Sandbox Code Playgroud)
这个例子工作,添加一个小数点(但我发现在doc中没有这样的要求):
String input = "20111203123456.978";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern( …Run Code Online (Sandbox Code Playgroud) 在DateTimeFormatter类文件说,有关当年的格式代码:
你在2004年; 04
y年的2004年; 04
...
年份:字母数决定了使用填充的最小字段宽度.如果字母数是2,则使用减少的两位数形式.对于打印,这将输出最右边的两位数字.对于解析,这将使用2000的基值进行解析,从而产生2000到2099(包括2000和2099)范围内的一年.如果字母数小于4(但不是2),则符号仅按负号年份输出,符合SignStyle.NORMAL.否则,如果超出了焊盘宽度,则根据SignStyle.EXCEEDS_PAD输出符号.
没有提到"时代".
那么究竟是什么这两个代码之间的差异,u对y,year对year-of-era?
什么时候应该使用类似这种模式的东西uuuu-MM-dd以及何时yyyy-MM-dd使用Java中的日期?
似乎那些知道使用的代码编写的示例代码uuuu,但为什么呢?
其他格式化类如遗产SimpleDateFormat只有yyyy,所以我很困惑为什么java.time uuuu为"年代" 带来了这个.
使用Java 8的新日期时间库,将字符串解析为日期的方法是使用DateTimeFormatter.LocalDate,LocalTime并且LocalDateTime都有一个静态解析方法,它接受一个String和一个格式化程序.一个潜在的问题是,如果你的DateTimeFormat不包含时间部分(或者对于DateTime,一个日期部分),即使你的模式匹配,你最终也会得到一个解析错误.
例
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("YYYY-MM-DD");
LocalDateTime dt = LocalDateTime.parse("2016-01-11", formatter);
Run Code Online (Sandbox Code Playgroud)
这将引发DateTimeParseException(如讨论这里与消息)
java.time.format.DateTimeParseException:
Text '2016-01-11' could not be parsed:
Unable to obtain LocalDateTime from TemporalAccessor
Run Code Online (Sandbox Code Playgroud)
这是一个有点无用的错误消息,因为文本可以解析,因为它匹配模式.相反,错误与它无法创建LocalDateTime的时间部分这一事实有关.将代码重构为以下代码:
LocalDateTime ldt = LocalDate.parse("2016-01-11", formatter).atStartOfDay());
Run Code Online (Sandbox Code Playgroud)
我的问题是,你说你有这样的通用方法
public static LocalDateTime getDate(String s, DateTimeFormatter format) {
...
}
Run Code Online (Sandbox Code Playgroud)
有没有办法确定需要调用哪个静态解析方法,通过应用一些默认逻辑将字符串强制转换为LocalDateTime?例如,如果日期仅使用午夜,如果时间仅使用今天,等等.
我有以下字符串:
18/07/2019 16:20
我尝试LocalDateTime使用以下代码将此字符串转换为:
val stringDate = expiration_button.text.toString()
val date = LocalDateTime.parse(stringDate, DateTimeFormatter.ofPattern("dd/MM/yyyy hh:mm")).toString()
Run Code Online (Sandbox Code Playgroud)
java.time.format.DateTimeParseException:无法解析文本“18/07/2019 04:30:00”:无法从 TemporalAccessor 获取 LocalDateTime
我缺少什么?
我需要能够存储没有时间组件的日期(年/月/日).这是一个日期的抽象概念,例如生日 - 我需要代表一年中的日期而不是特定的时刻.
我使用Java从一些输入文本解析日期,并需要存储在MySQL数据库中.无论数据库,应用程序或任何客户端处于什么时区,他们都应该看到相同的年/月/日.
我的应用程序将在具有与数据库服务器不同的系统时区的计算机上运行,而我无法控制.有没有人有一个优雅的解决方案,以确保我正确存储日期?
我可以想到这些解决方案,这些解决方案看起来都不是很好:
我想知道是否有可能在Java 8中解析时钟时间:分钟:秒?
例如
final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("HH:mm:ss");
final String str = "12:22:10";
final LocalDateTime dateTime = LocalDateTime.parse(str, formatter);
Run Code Online (Sandbox Code Playgroud)
我试过但得到这个例外:
Exception in thread "main" java.time.format.DateTimeParseException: Text '12:22:10' could not be parsed: Unable to obtain LocalDateTime from TemporalAccessor: {},ISO resolved to 12:22:10 of type java.time.format.Parsed
Run Code Online (Sandbox Code Playgroud) 如何获取 mySQL 时间戳格式mySQLtimestamp?
long epochNow = System.currentTimeMillis()/1000;
long epochWeek = 604800;
long date7daysAgo = epochNo2013 w - epochWeek;
String mySQLtimestamp = /* 2013-09-23:50:00 */
Run Code Online (Sandbox Code Playgroud) 基本上我有一个领域
private LocalDateTime date;
Run Code Online (Sandbox Code Playgroud)
从String解析.它提供的工作正常,String在末尾附加时间,但如果没有则会抛出异常.
DateTimeFormatter formatter = null;
if (value.matches("\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}")) {
formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
} else if (value.matches("\\d{4}-\\d{2}-\\d{2}")) {
formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
}
// Throws an exception for pattern "yyyy-MM-dd"
date = LocalDateTime.parse(value, formatter);
Run Code Online (Sandbox Code Playgroud)
而异常本身:
java.time.format.DateTimeParseException: Text '2000-06-29' could not be parsed: Unable to obtain LocalDateTime from TemporalAccessor: {},ISO resolved to 2000-06-29 of type java.time.format.Parsed
at pl.empirica.swissborg.service.util.CsvBeanUtils.copyList(CsvBeanUtils.java:75) ~[classes/:na]
at pl.empirica.swissborg.service.csv.CsvReaderService.persistCsvData(CsvReaderService.java:101) ~[classes/:na]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_91]
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) ~[na:1.8.0_91]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) ~[na:1.8.0_91]
at java.lang.reflect.Method.invoke(Unknown Source) ~[na:1.8.0_91] …Run Code Online (Sandbox Code Playgroud) 我编写了一段简单的代码来使用 java 8 api 解析日期。我还研究了有关此主题的各种其他堆栈溢出问题,但未能解决该错误。
package com.test.java8api;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.ResolverStyle;
import java.util.Locale;
public class Test {
public static void main(String[] args) {
// TODO Auto-generated method stub
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("EEE, MM/DD/YYYY - HH:mm", Locale.ENGLISH).withResolverStyle(ResolverStyle.STRICT);
LocalDateTime date = LocalDateTime.parse("Sun, 04/22/2018 - 09:45",formatter);
System.out.println(date);
}
}
Run Code Online (Sandbox Code Playgroud)
错误日志是
Exception in thread "main" java.time.format.DateTimeParseException: Text 'Sun, 04/22/2018 - 09:45' could not be parsed: Unable to obtain LocalDateTime from TemporalAccessor: {DayOfWeek=7, WeekBasedYear[WeekFields[SUNDAY,1]]=2018, MonthOfYear=4, DayOfYear=22},ISO resolved to 09:45 of type java.time.format.Parsed
at …Run Code Online (Sandbox Code Playgroud) 这看起来是一件非常简单的事情,但我没有这样做。
我有一个字符串模式,yyyyMMddHH我正在尝试解析2021061104为LocalDateTime
这是代码:
import java.time.Duration;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeFormatterBuilder;
import java.time.format.DateTimeParseException;
import java.time.temporal.ChronoField;
import java.time.temporal.ChronoUnit;
class Main {
public static void main(String[] args) {
String pattern = "yyyyMMddHH";
String date = "2021061104";
DateTimeFormatter formatter =
new DateTimeFormatterBuilder()
.parseDefaulting(ChronoField.HOUR_OF_DAY, 0)
.parseDefaulting(ChronoField.MINUTE_OF_HOUR, 0)
.parseDefaulting(ChronoField.SECOND_OF_MINUTE, 0)
.parseLenient()
.appendPattern(pattern)
.toFormatter();
LocalDateTime ldt = LocalDateTime.parse(date, formatter);
}
}
Run Code Online (Sandbox Code Playgroud)
它抛出这个异常:
Exception in thread "main" java.time.format.DateTimeParseException: Text '2021061104' could not be parsed at index 8
at java.time.format.DateTimeFormatter.parseResolved0(DateTimeFormatter.java:1949)
at java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1851)
at …Run Code Online (Sandbox Code Playgroud)