Display Date (not time) from Firestore Timestamp

前端 未结 4 1702
失恋的感觉
失恋的感觉 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条回答
  • 2021-01-16 15:01

    You can use Date.toLocaleString() like this:

    new Date(date).toLocaleString('en-EN', { year: 'numeric', month: 'long', day: 'numeric' });
    

    const timestamp = 1555477200000;
    console.log(
       new Date(timestamp).toLocaleString('en-EN', { year: 'numeric', month: 'long', day: 'numeric' })
    );

    0 讨论(0)
  • 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

    0 讨论(0)
  • 2021-01-16 15:09

    Simply use moment.js and use your required format

    date = moment();
    console.log(date.format("MMMM D, YYYY"));
    <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.1/moment.js"></script>

    0 讨论(0)
  • 2021-01-16 15:10

    You can do

    var time= timeStampFromFirestore.toDate(); 
    console.log(time); 
    console.log(time.toDateString());
    

    See the full documentation :

    toDateString()

    toDate()

    0 讨论(0)
提交回复
热议问题