获取特定格式的时间戳

Get Timestamp in specific format

我在 Azure SQL 数据库中保存了一个时间戳,格式为 2004-09-23 10:52:00。当我获取值时,我在使用 getString("last_updated_user") 的地方使用 sqlrowset 并获得类似“2004-09-23 10:52:00.0”的输出。当我尝试使用 getTimeStamp("last_updated_user") 时,我得到了微秒。有人可以根据一些内置函数(如 .format 或其他东西)帮助我将其格式化为“2004-09-23 10:52:00”,而不仅仅是通过替换或子字符串删除小数点吗?

解决方案使用 java.time,现代日期时间 API:

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;

public class Main {
    public static void main(String[] args) {
        String d = "2004-09-23 10:52:00.0";
        DateTimeFormatter dtfInput = DateTimeFormatter.ofPattern("u-M-d H:m:s.S", Locale.ENGLISH);
        LocalDateTime ldt = LocalDateTime.parse(d, dtfInput);

        DateTimeFormatter dtfOutput = DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm:ss", Locale.ENGLISH);
        String str = ldt.format(dtfOutput);
        System.out.println(str);
    }
}

输出:

2004-09-23 10:52:00

Online demo

了解有关 modern Date-Time API* from Trail: Date Time 的更多信息。


* 无论出于何种原因,如果您必须坚持Java 6 或Java 7,您可以使用ThreeTen-Backport which backports most of the java.time functionality to Java 6 & 7. If you are working for an Android project and your Android API level is still not compliant with Java-8, check Java 8+ APIs available through desugaring and

JDBC 4.2 和 java.time

由于我不了解 Azure SQL 数据库,所以我有点猜测。您报告的内容听起来像是您的数据库中有 SQL timestamp 或等效项。假设您的 JDBC 驱动程序符合 JDBC 4.2 从您的数据库中获取 LocalDateTime (不是字符串):

    LocalDateTime lastUpdatedUser
            = sqlrowset.getObject("last_updated_user", LocalDateTime.class);

我进一步假设 sqlrowsetjavax.sql.RowSet。要格式化为您想要的字符串,请使用像这样的格式化程序:

private static final DateTimeFormatter FORMATTER
        = DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm:ss");

现在我们可以做:

    System.out.println("LocalDateTime retrieved: " + lastUpdatedUser);
    String formatted = lastUpdatedUser.format(FORMATTER);
    System.out.println("Formatted:               " + formatted);

示例输出:

LocalDateTime retrieved: 2004-09-23T10:52
Formatted:               2004-09-23 10:52:00