1

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, nanoseconds=0)

I've tried a few variations to get the Date, but they all have the same output-

Due: Wed Apr 17 2019 06:10:21 GMT-0500 (Central Daylight Time)

<p>Due: ${Date(dueDate)}<br>
<p>Due: <time>${Date(dueDate)}</time><br>
<p>Due: <time type="date">${Date(dueDate)}</time><br>

How do I cut off the time part of the timestamp? (Ideally, I'd want "April 17, 2019", but if the day is in there that's fine too)

Bob Kelso
  • 40
  • 5
Caponigri
  • 27
  • 6

4 Answers4

2

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

1

You can do

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

See the full documentation :

toDateString()

toDate()

Bob Kelso
  • 40
  • 5
  • My date isn't in the DateTime format. It's in seconds from epoch. Is there a way to convert it so I can use this (I get 'invalid date' int he console) – Caponigri Apr 17 '19 at 11:54
  • @Caponigri If your variable is a TimeStamp from firestore, you can use firestoreTimestamp.toDate(). – Bob Kelso Apr 17 '19 at 12:02
  • @Caponigri `.toDate()` only return javaScript Date object, you must use `Date.toLocaleString()` to get the desired format like `"April 17, 2019"` – Fraction Apr 18 '19 at 13:09
  • I think that his question was about how to have a JavaScript Date Object from firestore TimeStamp actually. – Bob Kelso Apr 19 '19 at 13:06
1

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' })
);
Fraction
  • 6,401
  • 3
  • 15
  • 34
0

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>
Syed Mehtab Hassan
  • 1,196
  • 1
  • 7
  • 21