2017-02-20 6 views
0

나는 MongoDB 데이터베이스에 타임 스탬프를 가지고 있으며 읽을 수있는 날짜 형식으로 프린트하고 싶습니다. Java 나는 다음과 같은 코드를 가지고있는 MongoClient를 사용하여 :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를 사용할 수 있습니다. 필요에 따라 당신은 또한 MongoDB documentationLocalDateTime

1

으로 변경할 수 있습니다

BSON 날짜 유닉스 시대 이후 밀리 초 (1970 년 1 월 1 일)의 수를 나타내는 64 비트 정수입니다. 결과적으로 의 표시 가능 기간은 과거의 약 2 억 9 천만 년, 미래는 입니다.

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

를 또는 자바 API의 ObjectId.getDate()를 사용

ISODate("2012-10-15T21:26:17Z"), 예를 들면, ISODate 돌아 쉘의 getTimestamp() 기능을 사용합니다. 검색어로 사용하려면 다음 코드 예를 참조하십시오.

// 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)); 
관련 문제