What is the correct DateTimeFormatter pattern for datetimeoffset column

╄→尐↘猪︶ㄣ 提交于 2021-02-11 15:01:35

问题


What is the correct DateTimeFormatter pattern for querying a SQL Server table by a datetimeoffset column. When I execute the below query, I get results. What is the correct pattern I should use to run the same query from the java app?

SELECT *
FROM
       TABLE
WHERE
       CreateTimestamp >= '2020-07-06 06:00:00.0000000 +00:00'

Below is the java code snippet I use to convert the date:

public String convertToDatabaseColumn(OffsetDateTime offsetDateTime) {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd-HH.mm.ss.SSSSSS Z");
        return offsetDateTime.format(formatter);
    }

Below is the snippet that sets the parameter and executes the query

Date beginDt; // passed to the method as parameter
Date endDt; // passed to the method as parameter
OffsetDateTime beginDateTime = beginDt.toInstant().atOffset(ZoneOffset.UTC);
OffsetDateTime endDateTime = endDt.toInstant().atOffset(ZoneOffset.UTC);
params.put(BEG, convertToDatabaseColumn(beginDateTime));
params.put(END, convertToDatabaseColumn(endDateTime));
List<Map<String, Object>> newfuelList = sqlJdbcTemplate.queryForList(sqlForNewFuel, params);

I get the following exception

Caused by: com.microsoft.sqlserver.jdbc.SQLServerException: Conversion failed when converting date and/or time from character string.

回答1:


You need to use the pattern, yyyy-MM-dd HH.mm.ss.SSSSSS xxx. Check the following sentence from the documentation of DateTimeFormatter:

Pattern letter 'X' (upper case) will output 'Z' when the offset to be output would be zero, whereas pattern letter 'x' (lower case) will output '+00', '+0000', or '+00:00'.

Demo:

import java.time.LocalDateTime;
import java.time.OffsetDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;

public class Main {
    public static void main(String[] args) {
        // Test
        System.out.println(
                convertToDatabaseColumn(OffsetDateTime.of(LocalDateTime.of(2020, 7, 6, 6, 0, 0, 0), ZoneOffset.UTC)));
    }

    public static String convertToDatabaseColumn(OffsetDateTime offsetDateTime) {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH.mm.ss.SSSSSS xxx");
        return offsetDateTime.format(formatter);
    }
}

Output:

2020-07-06 06.00.00.000000 +00:00

Note: You also have a typo, - between dd and HH, in your pattern.



来源:https://stackoverflow.com/questions/64759668/what-is-the-correct-datetimeformatter-pattern-for-datetimeoffset-column

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!