2

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);
DMSJax
  • 1,709
  • 4
  • 22
  • 35

3 Answers3

2

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)

Niet the Dark Absol
  • 320,036
  • 81
  • 464
  • 592
1

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);

JsFiddle

Alex Shuraits
  • 432
  • 1
  • 5
  • 14
  • Although my own answer worked just fine, your answer is much cleaner and moment.js is compact enough to not impact processing/load time. So im good with accepting yours, thanks! – DMSJax Dec 03 '14 at 04:36
1

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);
DMSJax
  • 1,709
  • 4
  • 22
  • 35