且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在Java中将varchar转换为时间?

更新时间:2023-01-23 09:11:29

而是将其转换为秒并将其存储为有符号整数.您不能直接在字符串/varchars上执行数字运算,将其推回并返回可用格式的成本很高.那为什么不直接以这种格式存储它呢?

Rather convert it to seconds and store it as a signed integer. You can't do numerical operations directly on strings/varchars, it would be a high cost of massaging it forth and back to the useable format. Then why not just store it directly in that format?

这是一个启动示例,说明如何将CSV字段转换为秒:

Here's a kickoff example how to convert your CSV field to seconds:

public static int toSeconds(String time) throws ParseException {
    SimpleDateFormat positiveTime = new SimpleDateFormat("'['hh:mm:ss']'");
    SimpleDateFormat negativeTime = new SimpleDateFormat("'[-'hh:mm:ss']'");

    if (time.startsWith("[-")) {
        return -1 * (int) negativeTime.parse(time).getTime() / 1000;
    } else {
        return (int) positiveTime.parse(time).getTime() / 1000;
    }
}

这里是如何使用它并将其最终存储在DB中的方法:

Here's how you can use it and finally store it in DB:

String time1 = "[00:00:30]";
String time2 = "[- 00:10:20]";

int time1InSeconds = toSeconds(time1);
int time2InSeconds = toSeconds(time2);

// ...

preparedStatement = connection.prepareStatement("INSERT INTO tbl (col1, col2) VALUES (?, ?)");
preparedStatement.setInt(1, time1InSeconds);
preparedStatement.setInt(2, time2InSeconds);

要选择30秒以上的时间,只需执行以下操作:

To select times of over 30 seconds, just do like:

SELECT col1, col2 FROM tbl WHERE col1 > 30