programing

Firestore 날짜/시간 스탬프를 JS 날짜()로 변환하려면 어떻게 해야 합니까?

bestprogram 2023. 6. 21. 22:48

Firestore 날짜/시간 스탬프를 JS 날짜()로 변환하려면 어떻게 해야 합니까?

아래 날짜를 자바스크립트 Date() 객체로 변환하려고 합니다.내가 서버에서 그것을 돌려받았을 때, 그것은 Timestamp 객체입니다.

Firebase Firestore 콘솔의 스크린샷:

enter image description here

Firestore에서 반환된 개체 목록에서 다음을 시도할 때:

  list.forEach(a => {
    var d = a.record.dateCreated;
    console.log(d, new Date(d), Date(d))
  })

다음과 같은 출력이 표시됩니다. enter image description here

분명히 타임스탬프는 모두 다르며, 2018년 9월 9일(오늘)의 동일한 날짜가 아닙니다.왜 그런지도 잘 모르겠어요.new Date(Timestamp)는 결으로적이 .invalid date제가 JS 초보자라서요, 날짜나 타임스탬프가 잘못된 건가요?

DateFirestore의 개체에 대해 아무것도 알지 못합니다. 이 개체를 사용하여 무엇을 해야 할지도 모릅니다.

당신이 경우는려하를 .TimestampDate의 방법을 사용합니다.Timestamp.

사용할 수 있습니다.toDate() 기능합니다.toDateString()날짜 부분만 표시합니다.

const date = dateCreated.toDate().toDateString()
//Example: Friday Nov 27 2017

.toLocaleTimeString()

const time = dateCreated.toDate().toLocaleTimeString('en-US')
//Example: 01:10:18 AM, the locale part 'en-US' is optional

및 를 사용하여 앞뒤로 변환할 수 있습니다.

// Date to Timestamp
const t = firebase.firestore.Timestamp.fromDate(new Date());

// Timestamp to Date
const d = t.toDate();

Unix 타임스탬프를 JavaScript Date 개체로 변환하는 방법.

var myDate = a.record.dateCreated;
new Date(myDate._seconds * 1000); // access the '_seconds' attribute within the timestamp object

다른 답변 외에도 이렇게 할 수 있습니다.

    //date from firebase is represented as
    let time = {
      seconds: 1613748319,
      nanoseconds: 47688698687,
    }
    
    const fireBaseTime = new Date(
      time.seconds * 1000 + time.nanoseconds / 1000000,
    );
    const date = fireBaseTime.toDateString();
    const atTime = fireBaseTime.toLocaleTimeString();


    console.log(date, atTime);

이해주요를 사용해 .toDate()해서 method를 한 합니다.

   {{ row.orderDate.toDate() | date: 'dd MMM hh:mm' }}

마침내 필요한 것을 얻을 수 있었습니다.이 날짜는 다음 날짜로 반환 날짜:08/04/2020

new Date(firebase.firestore.Timestamp.now().seconds*1000).toLocaleDateString()
const timeStampDate = record.createdAt;
const dateInMillis  = timeStampDate._seconds * 1000

var date = new Date(dateInMillis).toDateString() + ' at ' + new Date(dateInMillis).toLocaleTimeString()

예: 출예력:Sat 11 Jul 2020 at 21:21:10

이는 다음과 같은 도움이 될 수 있습니다.

new Date(firebaseDate._seconds * 1000).toUTCString()

은 간단한방다사용화저타재장다임에를타것니입변로환임는하프탬스를 사용하는 것입니다.toMillis()화재 저장소 타임스탬프의 메서드입니다.
예: 예: 타임스탬프가 있습니다.
created_on : Timestamp { _seconds: 1622885490, _nanoseconds: 374000000 }

let epochTimestamp = created_on.toMillis()
//epochTimestamp = 1621081015081
//Now this timestamp can be used as usual javascript timestamp which is easy to manipulate.
let date = new Date(epochTimestamp) //date = Sat May 15 2021 17:46:55 GMT+0530 (India Standard Time)

에서 가져오는 에는 firestore가 .toDate()사용할 수 있는 방법.

list.forEach(a => {
  var d = a.record.dateCreated;
  console.log(d.toDate())
})

다음은 소방본부 문서에서 인용한 내용입니다.toDate()방법

타임스탬프를 JavaScript Date 개체로 변환합니다.Date 개체는 밀리초 단위의 정밀도만 지원하므로 이 변환으로 인해 정밀도가 손실됩니다.

이 타임스탬프와 동일한 시점을 밀리초의 정밀도로 나타내는 Date JavaScript Date 개체를 반환합니다.

https://firebase.google.com/docs/reference/js/firebase.firestore.Timestamp#todate

이것은 나에게 효과가 있습니다.

new Date(firebaseDate.toDate())

이것은 나에게 효과가 있습니다.

let val = firebase.timestamp // as received from the database, the timestamp always comes in an object similar to this - {_nanoseconds: 488484, _seconds: 1635367}
    (new Date( (val.time._seconds + val.time._nanoseconds * 10 ** -9) * 1000)).toString().substring(17, 21)

여기에 많은 답이 있지만, 신인으로서 저는 그들 대부분이 혼란스럽다는 것을 알았습니다.

그래서 저와 같은 초보자들을 위해, 여기 파이어스토어 날짜/타임스탬프를 자바스크립트 날짜()로 변환하는 방법과 왜 그렇게 해야 하는지에 대한 간단한 설명이 있습니다.

왜 개종합니까?

Firestore는 날짜를 Timestamp 개체로 저장합니다.Javascript Date() 개체와 다릅니다.

날짜() 개체를 Firestore로 보낸 다음 검색하면 Timestamp 개체가 반환되기 때문에 이 문제는 제게 혼란스러웠습니다.파이어스토어에 1달러를 건네주면 4쿼터를 돌려주는 것처럼 말입니다.동일한 금액(또는 동일한 날짜)이지만, 종이를 예상하고 금속을 얻는다면 혼란스러울 것입니다.

변환 방법

객체를 되어 있습니다.toDate

기억하세요, 참고: 기십시오하억.toDate 자바처보입다니럼트립크처럼 .toLocaleDateString()또는toDateString()하지만 그렇지 않습니다.JS Date() 객체와 Firestore Timestamp 객체는 동일하지 않으므로, 다른 하나에서 함수를 사용하려고 시도하는 나의 루키 실수를 범하지 마십시오.

하려면 Firestore Timestamp를 Javascript를 ..toDate()타임스탬프에 있습니다.

//get the document from Firestore
let fireStoreTimestamp = doc.data().nameOfYourDateField;
let javascriptDate = fireStoreTimestamp.toDate();

dayjs 라이브러리를 사용하여 Firebase Firestore 타임스탬프 초를 현지 시간으로 변환할 수 있습니다.

newDate =  dayjs.unix(date.seconds).$d;

시간이 걸릴 것입니다

date: { 
    seconds: 1639506600, 
    nanoseconds: 0 
}

로 변환합니다.

Date Sat Nov 16 2019 00:00:00 GMT+0530 (India Standard Time)

파이어스토어 날짜를 JS 날짜로 변환하여 웹 앱에 표시할 수 있는 답을 찾는 사람들을 돕기 위해.다음은 타이프스크립트를 사용한 예입니다...

import {
  Timestamp,
} from "firebase/firestore";

interface IStuff {
  createdAt: Timestamp;
}

const insertStuff = async (text: string) => {
    await addDoc(collection(db, "coolstuff"), {
      text,
      createdAt: serverTimestamp(),
    });
};

<p>{item.createdAt?.toDate().toDateString()}</p>

// OR

<p>{item.createdAt?.toDate().toLocaleTimeString()}</p>

타임스탬프를 Firestore에 저장하는 방법:

import * as firebaseAdmin from "firebase-admin";

const created = firebaseAdmin.firestore.FieldValue.serverTimestamp();

// type
created: FirebaseFirestore.Timestamp | FirebaseFirestore.FieldValue | undefined;

로서 다시 읽으려면js Date

const createDate = (created as FirebaseFirestore.Timestamp).toDate();

다음으로 다시 읽어보기RFC3339

const createDate = (created as FirebaseFirestore.Timestamp).toDate().toISOString();

이것은 화재 기지 시간 스탬프를 날짜로 변환하는 가장 우아하고 정확하며 쉬운 방법입니다(의존성 등이 필요하지 않음).

const date = new Intl.DateTimeFormat(
    'de-De', { 
           year: 'numeric', 
           month: 'numeric', 
           day: 'numeric', 
           hour: 'numeric', 
           minute: 'numeric' 
    }
).format(firebaseTimeStamp.toDate())

여기 필요한 모든 매개 변수가 포함된 치트 시트가 있습니다.

Waleed Tariq 답변을 확장하여 보다 읽기 쉬운 문자열을 얻습니다.

function formatDate(date) {
    const formatDate = new Date(
        date.seconds * 1000 + date.nanoseconds / 1000000
    );
    return formatDate.toLocaleTimeString('en-us', { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' });
}

const timeStamp = {nanoseconds: 184000000, seconds: 1664826910};

console.log(formatDate(timeStamp))

저도 같은 문제가 있었습니다.그리고 저는 다음과 같이 생각했습니다.

const createdAt = firebase.firestore.Timestamp.fromDate(new Date());

// then using dayjs library you can display your date as you want.

const formatDate = dayjs.unix(createdAt.seconds).format('YYYY-MM-DD');

출력은 다음과 같아야 합니다. 2020-08-04

밀리초를 잃지 않으려면 다음을 수행합니다.

var myDate = a.record.dateCreated;
new Date((myDate.seconds + myDate.nanoseconds * 10 ** -9) * 1000);

저는 각진 자세로 일합니다.

인터페이스와 필드 날짜: 날짜가 있습니다.

각 파이프 날짜가 작동하지 않음: order.date | 날짜: 'medium'

인터페이스에서 필드 날짜 유형을 변경합니다.

date: firebase.firestore.Timestamp

각도 파이프 날짜 작업, 그러나 함수가 Date()인 경우

order.date.toDate() | date:'medium'

아주 간단합니다.epoch 초를 Javascript 날짜 및 시간으로 변환하는 이 간단한 epoch 컨버터 기능을 사용합니다.

  function getUNIXTime(dt) {
    let unix = new Date(dt * 1000);
    return unix.toUTCString().slice(5, 16);   
}

를 하세요.timestamp.seconds날짜와 시간이 포함된 텍스트 문자열을 얻기 위해 필요에 따라 이 함수를 잘라냅니다.

일반적으로 모든 유형(예: loginDate:any) 및 toDate()를 사용하면 모든 프로젝트에서 문제 없이 작동했습니다.하지만 제 지난 프로젝트에서는 그렇지 않았습니다.Timestamp 개체에서 seconds가 _seconds 더 이상(Firebase 8.6.8)인 것을 보았습니다.이러한 유형의 변경이 영향을 미쳤을 수 있습니다.저도 잘 모르겠지만 시간이 없어서 대체 솔루션을 사용했습니다.사용자 지정 파이프.대안으로 사용할 수 있습니다.

import { Pipe, PipeTransform } from '@angular/core';
import { formatDate } from '@angular/common';

@Pipe({
  name: 'timestamp'
})
export class TimestampPipe implements PipeTransform {

  transform(value: any, format?: string) {

    if (!value) { return ''; }
    if (!format) { format = 'dd MMM  yy'; }

    return formatDate(value._seconds * 1000, format, 'tr');
  }
}

그리고.

{{ item.endDate | timestamp}}

P.S. 유형은 이 파이프에서 중요하지 않습니다.loginDate: any 또는 loginDate:데이트 잘하세요.

웹 Firestore 타임스탬프:

function dateToFirestoreTimestamp(dateString = ''){
        var timestampDate = new Date();     // this will return current date-time
        if(dateString != ''){
            // this will return timestamp according to provided date-time
            dateString = dateString.replace(' ', 'T');
            timestampDate = new Date(dateString);
        } 
        timestampDate = firebase.firestore.Timestamp.fromDate(timestampDate);
        return timestampDate;
    }

이것은 firestore timestamp와 Javascript Date() 객체 간의 다른 점입니다.만약 당신이 firestore timestamp에서 javascript Date() 객체를 사용하고 싶다면, 나는 다음과 같이 합니다:

const foo = new Date(firestoreTimestamp.toDate());

그러면 평소처럼 javascript Date() 개체를 사용할 수 있습니다.다음은 몇 가지 참조 사항입니다.

https://www.w3schools.com/jsref/jsref_obj_date.asp

예를 들어 Date() 개체에서 다음 문자열 형식으로 날짜를 검색하려고 합니다.

const foo = new Date(firestoreTimestamp.toDate());
foo.toLocaleDateString();

기타.

언급URL : https://stackoverflow.com/questions/52247445/how-do-i-convert-a-firestore-date-timestamp-to-a-js-date