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

3 Answers 3

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)

Sign up to request clarification or add additional context in comments.

Comments

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

1 Comment

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.