英文:
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);
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论