PDA

View Full Version : real time date and time in javascript



ianhaney
01-09-2017, 04:32 PM
Hi

I have the following script to display real time date and time and works perfect but how do I add th or st or nd depending on the date, for example it currently read Monday January 9 2017 16:31:49 but be good if could be Monday January 9th 2017 16:31:49

The code is below



function date_time(id)
{
date = new Date;
year = date.getFullYear();
month = date.getMonth();
months = new Array('January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December');
d = date.getDate();
day = date.getDay();
days = new Array('Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday');
h = date.getHours();
if(h<10)
{
h = "0"+h;
}
m = date.getMinutes();
if(m<10)
{
m = "0"+m;
}
s = date.getSeconds();
if(s<10)
{
s = "0"+s;
}

function nth(d) {
if(d>3 && d<21) return 'th'; // thanks kennebec
switch (d % 10) {
case 1: return "st";
case 2: return "nd";
case 3: return "rd";
default: return "th";
}
}

result = ''+days[day]+' '+months[month]+' '+d+' '+year+' '+h+':'+m+':'+s;
document.getElementById(id).innerHTML = result;

setTimeout('date_time("'+id+'");','1000');
return true;
}


Thank you in advance

Beverleyh
01-09-2017, 05:09 PM
result = ''+days[day]+' '+months[month]+' '+d+nth(d)+' '+year+' '+h+':'+m+':'+s;

ianhaney
01-09-2017, 05:36 PM
Thank you so much really appreciate the reply and help

SerDrake
01-09-2017, 07:30 PM
Yep, the Beverleyh answer is correct but that code... it's weird.

I have some advice for you:
Have a look these opensources libraries, Moment.js (http://momentjs.com/) and Date.js (http://www.datejs.com/)!
All you need to better manage the dates.

ianhaney
01-09-2017, 08:20 PM
Yep, the Beverleyh answer is correct but that code... it's weird.

I have some advice for you:
Have a look these opensources libraries, Moment.js (http://momentjs.com/) and Date.js (http://www.datejs.com/)!
All you need to better manage the dates.

I did look at moment.js but was unsure if it is real time so the seconds rather than having to refresh the page so get the current time

sonvi.belani
01-12-2017, 11:17 AM
Hi,
you should try this code:

$(document).ready(function() {
var interval = setInterval(function() {
var momentNow = moment();
$('#date-part').html(momentNow.format('YYYY MMMM DD') + ' '
+ momentNow.format('dddd')
.substring(0,3).toUpperCase());
$('#time-part').html(momentNow.format('A hh:mm:ss'));
}, 100);
});

Thanks,
sonvi.belani