firestore에서 timestamp, Date 다루기

바람찬허파·2023년 1월 22일
1

firestore의 timestamp 문제

다음과 같이 startTime에 new Date() 객체를 route로 보내주고,


firebase 내 document에 요소로 add 해주었다.
이후 가족회의 기록 돌아보기 기능을 통해 앞서 add했던 내용을 가져오고자 하였는데,

🚨new Date() 객체에서 사용 가능한 new Date().toLocaleString() 함수가 사용되지 않았다.
log에는

 LOG  StartTime 구조: {"nanoseconds": 270000000, "seconds": 1674377309}
 LOG  [TypeError: doc.data().startTime.toLocaleTimeString is not a function. (In 'doc.data().startTime.toLocaleTimeString()', 'doc.data().startTime.toLocaleTimeString' is undefined)]

다음과 같이 nanoseconds와 seconds 의 key값과 value의 구조를 띄고 있었다. 또한 toLocaleTimeString은 정의되지 않은 함수라는 에러가 떴다.


log를 찍어보니,
new Date() => startTime에 저장 => 파라미터로 넘겨줌 => firestore에 저장 => 해당 document 읽기의 과정에서
firestore에 저장한 부분이 잘못되었다.

해결방법

firstore의 설명에 따르면

new Timestamp ( seconds :  number ,  nanoseconds :  number ) : Timestamp



🫁 timestamp은 프롤레틱 그레고리력을 통해 인코딩 되고,윤초가 smeared(얼룩진) 된다고 한다. (어쩐지 nanoseconds로 계산했더니 1970년이 나오더라..)

때문에 해당 Timestamp를 js의 Date 객체로 변환하기 위해서는

toDate()

라는 메소드를 사용하면 된다. 추가로 Date 객체가 millisecond 예측을 지원하기 때문에 loss를 발생할 수 있다고 한다는 점도 알게 되었다. ( 여기서 왜 prediction이라 표현 하는지는 의문)

0개의 댓글