Javascript date getDate() method returns the day of the month for the specified date according to local time. The value returned by getDate() is an integer between 1 and 31.
now() method is used to return the number of milliseconds elapsed since January 1, 1970, 00:00:00 UTC. Since now() is a static method of Date, it will always be used as Date.
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.
var now = new Date();
now.format("dd/MM/yyyy hh:mm TT");
Get full details here: Flagrant Badassery » JavaScript Date Format
Date().toLocaleString()
returns this: 7/31/2018, 12:58:03 PM
Pretty close - just drop the comma and the seconds:
new Date().toLocaleString().replace(",","").replace(/:.. /," ");
Results: 7/31/2018 12:58 PM
function pad_2(number)
{
return (number < 10 ? '0' : '') + number;
}
function hours(date)
{
var hours = date.getHours();
if(hours > 12)
return hours - 12; // Substract 12 hours when 13:00 and more
return hours;
}
function am_pm(date)
{
if(date.getHours()==0 && date.getMinutes()==0 && date.getSeconds()==0)
return ''; // No AM for MidNight
if(date.getHours()==12 && date.getMinutes()==0 && date.getSeconds()==0)
return ''; // No PM for Noon
if(date.getHours()<12)
return ' AM';
return ' PM';
}
function date_format(date)
{
return pad_2(date.getDate()) + '/' +
pad_2(date.getMonth()+1) + '/' +
(date.getFullYear() + ' ').substring(2) +
pad_2(hours(date)) + ':' +
pad_2(date.getMinutes()) +
am_pm(date);
}
Code corrected as of Sep 3 '12 at 10:11
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With