SQL时间戳无法转换为OffsetDateTime。

huangapple go评论67阅读模式
英文:

SQL timestamp not converting to OffsetDateTime

问题

OffsetDateTime dateColumn = OffsetDateTime.parse(row.get("date_column").toString(), dateTimeFormatter);

日期格式示例为:2023-07-17 12:22:02.626948

英文:

I have a sql timestamp that is being returned from a query in java. I need this date as an OffsetDateTime type, but my attempts to parse it have failed. I've tried the following. What other steps do I need to take?

I'm iterating through the sql response list from my jdbcTemplate. I'm able to access other string rows just fine, but when I try to include this code the query fails. date_column refers to the column in the table and my query is returning the data. It's just not being transformed to OffsetDateTime.

DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ISO_OFFSET_DATE_TIME;
OffsetDateTime dateColumn = OffsetDateTime.parse(row.get("date_column").toString(), dateTimeFormatter);

The row.get response returns this date format 2023-07-17 12:22:02.626948

答案1

得分: 1

如果在数据库中没有存储偏移量(正如你所说,返回的是类似于 2023-07-17 12:22:02.626948 的格式),那么你可以在一些假设的基础上获得一个 OffsetDateTime。例如,以下代码段在假设 LocalDateTime 是在 UTC 时才能正常工作:

String s = "2023-07-17 12:22:02.626948";
DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.nnnnnn");
LocalDateTime localDateTime = LocalDateTime.parse(s, dateTimeFormatter);
OffsetDateTime offsetDateTime = localDateTime.atOffset(ZoneOffset.UTC);
英文:

If in the db you don't have stored the offset (as you say, you are returning something like 2023-07-17 12:22:02.626948), then you can obtain a OffsetDateTime only with some assumptions. For example, the following snippet will work if you assume that the LocalDateTime is at UTC:

String s = "2023-07-17 12:22:02.626948";
DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.nnnnnn");
LocalDateTime localDateTime = LocalDateTime.parse(s, dateTimeFormatter);
OffsetDateTime offsetDateTime = localDateTime.atOffset(ZoneOffset.UTC);

huangapple
  • 本文由 发表于 2023年7月18日 04:40:22
  • 转载请务必保留本文链接:https://go.coder-hub.com/76707934.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定