Jivko Dimitrov
Jivko Dimitrov

Reputation: 15

properly display date from database using javascript

I have a creation_date displayed in my database in this format

2014-02-03 15:59:07

but when I'm displaying it in my page the format is

2014-02-10T18:16:43.000Z

What do I need to do to display it properly? I'm using JavaScript. Thanks

Upvotes: 1

Views: 733

Answers (3)

rutvik patel
rutvik patel

Reputation: 1

Get Date from MongoDB

InvoiceModel.find({})
    .sort({ dueDate: -1 })
    .exec((err, data) => {
      if (!err) {
        console.log(data[0].dueDate);
        const dt = data[0].dueDate.toDateString();
        const date = new Date(dt);
        console.log(dt);

        console.log(date.getDate());
        console.log(date.getMonth() + 1);
        console.log(date.getFullYear());
       
        res.json({ status: 200, message: " Invoice are received", data: data });
      } else {
        res.json({ status: 401, message: err, data: {} });
      }
    });
 

Upvotes: 0

Tudor Zgureanu
Tudor Zgureanu

Reputation: 725

date = new Date("2014-02-10T18:16:43.000Z");

and then use some of Date methods, for example

date.toDateString() will show "Mon Feb 10 2014", or you could format by yourself by composing your own format. Like:

 formattedDate = date.getDate()+"."+(date.getMonth()+1)+"."+date.getFullYear();

and output will be "10.2.2014"

Upvotes: 3

zkanoca
zkanoca

Reputation: 9918

First select date data as unix timestamp multiplying 1000 to get miliseconds;

SELECT UNIX_TIMESTAMP(your_date_col) * 1000 AS ts ...

Then get it to Javascript (assuming that you use PHP):

var date2display = new Date(<?=$row['ts']?>);

Upvotes: 0

Related Questions