gpt4 book ai didi

java - 格式化 MongoDB 时间戳

转载 作者:行者123 更新时间:2023-12-02 03:01:01 25 4
gpt4 key购买 nike

我的时间戳位于 MongoDB 中数据库,我想以可读的日期格式漂亮地打印它们。使用JavaMongoClient我有以下代码:

import com.mongodb.MongoClient;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoCursor;
import com.mongodb.client.MongoDatabase;
import org.bson.Document;

import java.sql.Timestamp;

public class MongoDBTest
{
public static void main(String[] arguments)
{
MongoClient client = new MongoClient("127.0.0.1", 27017);
String databaseName = "my_database";
MongoDatabase database = client.getDatabase(databaseName);
String collectionName = "my_collection";
MongoCollection collection = database.getCollection(collectionName);

try (MongoCursor<Document> cursor = collection.find().iterator())
{
while (cursor.hasNext())
{
String json = cursor.next().toJson();
Document document = Document.parse(json);
String stringTimestamp = document.get("timestamp").toString();
Timestamp timestamp = new Timestamp(Long.parseLong(stringTimestamp));
System.out.println("Timestamp: " + stringTimestamp + " Formatted: " + timestamp);
}
}
}
}

打印的时间戳似乎不正确,因为它们都来自 1970但不应该是:

Timestamp: 1357466440 Formatted: 1970-01-16 18:04:26.44
Timestamp: 1357466449 Formatted: 1970-01-16 18:04:26.449
Timestamp: 1357466457 Formatted: 1970-01-16 18:04:26.457
Timestamp: 1357466462 Formatted: 1970-01-16 18:04:26.462
Timestamp: 1357466469 Formatted: 1970-01-16 18:04:26.469
Timestamp: 1357466469 Formatted: 1970-01-16 18:04:26.469
Timestamp: 1357466477 Formatted: 1970-01-16 18:04:26.477
Timestamp: 1357466477 Formatted: 1970-01-16 18:04:26.477

如何获取“真实”格式化日期?

最佳答案

看起来您有以秒为单位的时间戳值。乘以 1000 即可得到毫秒单位。

 String stringTimestamp = document.get("timestamp").toString();
Timestamp timestamp = new Timestamp(Long.parseLong(stringTimestamp) * 1000);
Instant instant = timestamp.toInstant();

从这里您可以使用DateTimeFormatter进行格式化。根据您的需要,您还可以更改为 LocalDateTime

关于java - 格式化 MongoDB 时间戳,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42349639/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com