Reputation: 1727
1.) Is there a built in formatting option in javascript to display time obtained from Date() to be 12 hr format?
2.) With the script below the minutes and seconds field are displayed as 1 digit format when the values are less than 10. Is there a way force 2 digit reporting on the minutes/seconds values so that 1.. 2... 3... displays as 01... 02... 03... and so on....
function updateTime(){
var dt = new Date();
var weekday = new Array(7);
weekday[0]= 'Sunday';
weekday[1] = 'Monday';
weekday[2] = 'Tuesday';
weekday[3] = 'Wednesday';
weekday[4] = 'Thursday';
weekday[5] = 'Friday';
weekday[6] = 'Saturday';
var time = weekday[dt.getDay()] + ' ' + dt.getDate() + '/' + dt.getMonth() + '/' + dt.getFullYear() + ' ' +dt.getHours() + ':' + dt.getMinutes() + ':' + dt.getSeconds();
document.getElementById('dttime').innerHTML = time;
}
setInterval(updateTime, 1000);
Upvotes: 2
Views: 129
Reputation: 1727
Turns out I did miss a built in function, here is what I ended up with that works as needed.
function updateTime(){
var dt = new Date();
var n = dt.toLocaleTimeString(); <-- added new var converts dt to local time string
var weekday = new Array(7);
weekday[0]= 'Sunday';
weekday[1] = 'Monday';
weekday[2] = 'Tuesday';
weekday[3] = 'Wednesday';
weekday[4] = 'Thursday';
weekday[5] = 'Friday';
weekday[6] = 'Saturday';
var time = weekday[dt.getDay()] + ' ' + dt.getDate() + '/' + dt.getMonth() + '/' + dt.getFullYear() + ' ' + n; <-- removed getMin/GetSec and replaced with N variable.
document.getElementById('dttime').innerHTML = time;
}
setInterval(updateTime, 1000);
Upvotes: 1
Reputation: 442
Make your life simple. Use Moment.js
function updateTime(){
var time = moment().format('MMMM Do YYYY, h:mm:ss a');
document.getElementById('dttime').innerHTML = time;
}
setInterval(updateTime, 1000);
Upvotes: 1
Reputation: 324800
1) Sort of. Simply do ""+dt
and you'll get the date formatted according to the browser's locale. In theory at least, if your computer is set to 12-hour, then the result will be too.
2) You can zero-pad with ("0"+dt.getHours()).slice(-2)
Upvotes: 2