2017-02-20 583 views
0

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

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 

如何获得“真正的”格式化的日期?

回答

1

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

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

从这里您可以使用DateTimeFormatter进行格式化。根据你的需要,你也可以变成LocalDateTime

1

MongoDB documentation

BSON日期是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的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));