I'm using express in nodejs for my backend and react for my frontend.
In the backend, I use Date.now() then add toLocaleDateString() to make it format as 12/25/2021. For some reason, Date.now() is behaving oddly when I insert into MongoDB.
A simple "new Date()" is returning as "2021-12-20T05:01:48.055Z", and Date.now() is returning the exact same thing... why is this happening? It never happened before.
When I type Date.now() in my web browser console, it returns the right thing.
Here's my code:
export const postSnippet = async function (req, res) {
// Create new snippet
let snippet = new Snippet({
title: req.body.title,
code: req.body.code,
creator: req.body.creator,
createdDate: Date.now(),
updatedDate: Date.now(),
collections: req.body.collections,
});
try {
// Save snippet to database
await snippet.save();
return res.status(201).json({ message: "Snippet created", snippet });
} catch (error) {
// Error handling
return res.status(500).json({
message: "Failure creating snippet.",
error: error.message,
});
}
};
Thanks to Cameron, I found the solution.
Inside render() of Snippet.js, I added this up top, before return.
let newUpdatedDate = new Date(this.props.updatedDate);
let updatedDate = newUpdatedDate.toLocaleDateString();
Then adding to DIV
<div className="snippet-date">
Last updated {updatedDate}
</div>
Thanks for the support
Thank you guys so much! I'm new to JavaScript but so far I am loving it. Stackoverflow has been an amazing website to get help. I'm learning so much. I believe this will open me up to a variety of new clients. Before this, all I knew was HTML/CSS with PHP/MySQL for backend/database. I used to love PHP religiously but now my favorite is Nodejs, and that's because you can learn and build literally ANYTHING you put your mind to