我正在尝试将Unix时间戳转换为日期。
final DateTimeFormatter formatter =
DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
final String startdate = Instant.ofEpochSecond(Long.parseLong(requestVO.getStartDate().toString()))
.atZone(ZoneId.of("GMT-4"))
.format(formatter);
final String enddate = Instant.ofEpochSecond(Long.parseLong(requestVO.getEndDate().toString()))
.atZone(ZoneId.of("GMT-4"))
.format(formatter);以上就是我在DateTimeFormatter和requestVO.getStartDate()中使用的date格式,它给出了Date类型值。
and ceo.erx_date between '"+startdate+"' and '"+enddate+"' 获取But时没有编译错误,给出数字格式异常。
发布于 2020-01-28 13:05:27
如果requestVo.getStartDate()返回一个Date对象,那么您的错误在这里:
Long.parseLong(requestVo.getStartDate())正如documentation所说,Long.parseLong(String)抛出
NumberFormatException -如果字符串不包含可解析的长整型。
试试这个:
Long.parseLong(requestVo.getStartDate().getTime())每种情况下都有两件事:
NullPointerException:检查您的日期是否为null,当用编写e查询时,使用preparedStatement而不是字符串连接
使用PreparedStatement代替Statement至少有两个原因
Statement更快:因为Statement每次都被编译和执行,而PreparedStatment只编译一次PreparedStatement的情况下,从PreparedStatement的角度来看,你是安全的发布于 2020-01-28 13:31:38
tl;dr
myJavaUtilDate // The terrible `java.util.Date` class is the legacy way to represent a moment in UTC.
.toInstant() // `Instant` is modern way to represent a moment in UTC.
.atZone( // Adjust from UTC to some time zone.
ZoneId.of( "America/Martinique" ) // Specify the time zone you had in mind for an offset of four hours behind UTC.
) // Returns a `ZonedDateTime` object.
.format( // Generate text representing the value of our `ZonedDateTime` object's content.
DateTimeFormatter.ISO_LOCAL_DATE_TIME // A predefined formatter per ISO 8601 that omits any indication of time zone or offset-from-UTC.
)
.replace(
"T" , // Standard ISO 8601 formats use a `T` between the date and time-of-day portions.
" "
) // Returns a `String`. java.util.Date::toInstant
requestVO.getStartDate()提供日期类型值。
你工作太努力了。
将可怕的Date类对象转换为它的现代替代品Instant。请注意,如何为遗留类提供新方法,以便将转换为现代java.time类,或将其转换为现代were类。在旧类上查找to…和from…方法。在本例中为Date::toInstant。
Instant instant = myJavaUtilDate.toInstant() ;分区与偏移
.atZone(ZoneId.of("GMT-4"))
不,-4不是时区。这是一个偏移量。
与UTC的偏移量仅仅是在本初子午线之前或之后的几个小时-分钟-秒。
时区要多得多。时区是特定地区的人们所使用的偏移量的过去、现在和未来变化的历史。时区包含Continent/Region格式的名称,如Asia/Kolkata或Pacific/Auckland。
最好使用时区,而不是仅仅使用偏移量。首先,你可能对偏移量的估计是错误的。通过使用时区,java.time将确定在您的预期时刻生效的偏移量。
偏移UTC四小时的区域
在-4之前,您可能会想到一个时区,比如America/Martinique、America/Aruba或America/Puerto_Rico。
ZoneId z = ZoneId.of( "America/Puerto_Rico" ) ;Instant + ZoneId ZonedDateTime➡
应用该ZoneId来生成ZonedDateTime对象。同样的时刻,不同的挂钟时间。
ZonedDateTime zdt = instant.atZone( z ) ;生成文本
生成标准ISO 8601格式的字符串,并对其进行适当扩展以将区域名称附加到方括号中。
String output = zdt.toString() ;但是您想要一个类似于ISO 8601的格式,但是中间没有T,也没有偏移/区域指示器。我不建议在不表示时区或偏移量的情况下报告时刻。但如果你坚持:
String output =
zdt
.format( DateTimeFormatter.ISO_LOCAL_DATE_TIME )
.replace( "T" , " " )
;https://stackoverflow.com/questions/59942203
复制相似问题