格式化MongoDB时间戳

时间:2017-02-20 16:28:45

标签: java mongodb

我在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

如何获得&#34;真实&#34;格式化的日期?

2 个答案:

答案 0 :(得分:1)

看起来你有几秒钟的timestamp值。乘以1000得到毫秒。

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

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

答案 1 :(得分:1)

MongoDB documentation

  

BSON Date是一个64位整数,表示数字   自Unix时代以来的毫秒(1970年1月1日)。这导致了   可表示的日期范围约为2.9亿年过去和   将来

使用shell getTimestamp()函数返回ISODate,例如ISODate("2012-10-15T21:26:17Z")

ObjectId.prototype.getTimestamp = function() {
    return new Date(parseInt(this.toString().slice(0,8), 16)*1000);
}

或者使用其Java API&#39; ObjectId.getDate()。如果您想将此用于查询,请参阅以下示例摘录:

// create a date of yesterday
DateTime yesterday = new DateTime().minusDays(1);
Long timestamp = yesterday.getMillis() / 1000L;
String oidString = Long.toHexString(l) + "0000000000000000";

// now find anything newer than that date
ObjectId id = new ObjectId(oidString);
DBObject result = new BasicDBObject("_id", new BasicDBObject("$gt", id));