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 OverflowHow to get datetime in JavaScript? - Stack Overflow
Convert datetime to valid JavaScript date - Stack Overflow
How do we work with the date and datetime in JS?
Getting current date and time in JavaScript - Stack Overflow
Videos
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.
The failure is up to the browser implementation's handling of Date.parse and how they allow for date strings not conform the date standards
ECMAScript defines a string interchange format for date-times based upon a simplification of the ISO 8601 calendar date extended format.
The format is as follows:YYYY-MM-DDTHH:mm:ss.sssZ
So we can force your string into this
Copyconst getDateFromString = str => {
const [date,time] = str.split(" ");
// reformat string into YYYY-MM-DDTHH:mm:ss.sssZ
str = `${date}T${time}.000Z`
return new Date(str);
};
let date = getDateFromString('2011-07-14 11:23:00');
console.log(date)
Run code snippetEdit code snippet Hide Results Copy to answer Expand
Older answer:
As for your format, some OSX browsers insist on the dashes being slashes.
This works everywhere including Safari 5 and Firefox 5 on OS X.
UPDATE: Fx Quantum (54) has no need for the replace, but Safari 11 is still not happy unless you convert as below
Copyvar date_test = new Date("2011-07-14 11:23:00".replace(/-/g,"/"));
console.log(date_test);
Run code snippetEdit code snippet Hide Results Copy to answer Expand
One can use the getmonth and getday methods to get only the date.
Here I attach my solution:
Copyvar fullDate = new Date(); console.log(fullDate);
var twoDigitMonth = fullDate.getMonth() + "";
if (twoDigitMonth.length == 1)
twoDigitMonth = "0" + twoDigitMonth;
var twoDigitDate = fullDate.getDate() + "";
if (twoDigitDate.length == 1)
twoDigitDate = "0" + twoDigitDate;
var currentDate = twoDigitDate + "/" + twoDigitMonth + "/" + fullDate.getFullYear(); console.log(currentDate);
Run code snippetEdit code snippet Hide Results Copy to answer Expand
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.
.getMonth() returns a zero-based number so to get the correct month you need to add 1, so calling .getMonth() in may will return 4 and not 5.
So in your code we can use currentdate.getMonth()+1 to output the correct value. In addition:
.getDate()returns the day of the month <- this is the one you want.getDay()is a separate method of theDateobject which will return an integer representing the current day of the week (0-6)0 == Sundayetc
so your code should look like this:
var currentdate = new Date();
var datetime = "Last Sync: " + currentdate.getDate() + "/"
+ (currentdate.getMonth()+1) + "/"
+ currentdate.getFullYear() + " @ "
+ currentdate.getHours() + ":"
+ currentdate.getMinutes() + ":"
+ currentdate.getSeconds();
JavaScript Date instances inherit from Date.prototype. You can modify the constructor's prototype object to affect properties and methods inherited by JavaScript Date instances
You can make use of the Date prototype object to create a new method which will return today's date and time. These new methods or properties will be inherited by all instances of the Date object thus making it especially useful if you need to re-use this functionality.
// For todays date;
Date.prototype.today = function () {
return ((this.getDate() < 10)?"0":"") + this.getDate() +"/"+(((this.getMonth()+1) < 10)?"0":"") + (this.getMonth()+1) +"/"+ this.getFullYear();
}
// For the time now
Date.prototype.timeNow = function () {
return ((this.getHours() < 10)?"0":"") + this.getHours() +":"+ ((this.getMinutes() < 10)?"0":"") + this.getMinutes() +":"+ ((this.getSeconds() < 10)?"0":"") + this.getSeconds();
}
You can then simply retrieve the date and time by doing the following:
var newDate = new Date();
var datetime = "LastSync: " + newDate.today() + " @ " + newDate.timeNow();
Or call the method inline so it would simply be -
var datetime = "LastSync: " + new Date().today() + " @ " + new Date().timeNow();
To get time and date you should use
new Date().toLocaleString();
>> "09/08/2014, 2:35:56 AM"
To get only the date you should use
new Date().toLocaleDateString();
>> "09/08/2014"
To get only the time you should use
new Date().toLocaleTimeString();
>> "2:35:56 AM"
Or if you just want the time in the format hh:mm without AM/PM for US English
new Date().toLocaleTimeString('en-US', { hour12: false,
hour: "numeric",
minute: "numeric"});
>> "02:35"
or for British English
new Date().toLocaleTimeString('en-GB', { hour: "numeric",
minute: "numeric"});
>> "02:35"
Read more here.