Display Date (not time) from Firestore Timestamp

前端 未结 4 1736
失恋的感觉
失恋的感觉 2021-01-16 14:56

I\'m pulling a timestamp from a Firestore database, and I only want to display the date to the user. The original timestamp is

Timestamp(seconds=1555477200,         


        
4条回答
  •  猫巷女王i
    2021-01-16 15:08

    If you have a particular format for date, you can do

    function getDate (timestamp=Date.now()) {
        const date = new Date(timestamp);
        let dd = date.getDate();
        let mm = date.getMonth()+1; //January is 0!
        const yyyy = date.getFullYear();
    
        if(dd<10) {
            dd = '0'+dd
        } 
    
        if(mm<10) {
            mm = '0'+mm
        } 
        // Use any date format you like, I have used YYYY-MM-DD
        return `${yyyy}-${mm}-${dd}`;
    }
    getDate(1555477200000);
    // -> 2019-04-17
    

    Alternatively, you can also do:

    const time = new Date(1555477200000); 
    // ->  Wed Apr 17 2019 10:30:00 GMT+0530 (India Standard Time)
    const date = time.toDateString();
    // -> Wed Apr 17 2019
    

    P.S: I have used ES6 here. If you are working on ES5, use babel's online transpiler to convert.

    Link: https://babeljs.io/repl

提交回复
热议问题