Semantically, you're probably looking for the one-liner
new Date().toLocaleString()
which formats the date in the locale of the user.
If you're really looking for a specific way to format dates, I recommend the moment.js library.
Answer from Andrew Mao on Stack OverflowVideos
Semantically, you're probably looking for the one-liner
new Date().toLocaleString()
which formats the date in the locale of the user.
If you're really looking for a specific way to format dates, I recommend the moment.js library.
If the format is "fixed" meaning you don't have to use other format you can have pure JavaScript instead of using whole library to format the date:
//Pad given value to the left with "0"
function AddZero(num) {
return (num >= 0 && num < 10) ? "0" + num : num + "";
}
window.onload = function() {
var now = new Date();
var strDateTime = [[AddZero(now.getDate()),
AddZero(now.getMonth() + 1),
now.getFullYear()].join("/"),
[AddZero(now.getHours()),
AddZero(now.getMinutes())].join(":"),
now.getHours() >= 12 ? "PM" : "AM"].join(" ");
document.getElementById("Console").innerHTML = "Now: " + strDateTime;
};
<div id="Console"></div>
The variable strDateTime will hold the date/time in the format you desire and you should be able to tweak it pretty easily if you need.
I'm using join as good practice, nothing more, it's better than adding strings together.
As far as I know the database stores the datetimes in UTC format.
We have some datepickers and datetimepickers, we want to show the exact time and date the user selected, no matter where the user is, so we don't care about timezones, however when parsing the dates, such as
let date = new Date('2021-12-14')
Sometimes it'll parse as December 13th instead of 14th depending on my timezone.
How can I parse it without caring about the timezone, and how should I send it to the backend?
As I said this is completely timezone-agnostic, I just want to keep the exact correct date, same applies with the time for timepickers, I don't want to convert to local, I just want to keep the exact time the user selected for everything.