Hello.

I am trying to create a javascript date/time script to display the current GMT date, but obviously because javasceipt is client side it displays the clients current date not the GMT date.

Does anyone know how i can get javascript to show the current GMT date to anyone (even people not in the GMT timezone).

Here is my script as it stands now;

function Time()
{	
	var d = new Date();
	
	var seconds1 = d.getSeconds();
	if(seconds1 < 10) {
		var seconds = "0" + d.getSeconds();
	} else {
		var seconds = d.getSeconds();
	}
	
	var mins1 = d.getMinutes();
	if(mins1 < 10) {
		var mins = "0" + d.getMinutes();
	} else {
		var mins = d.getMinutes();
	}
	
	var hours1 = d.getHours();
	if(hours1 < 10) {
		var hours = "0" + d.getHours();
	} else {
		var hours = d.getHours();
	}
	
	var day1 = d.getDate();
	if(day1 < 10) {
		var day = "0" + d.getDate();
	} else {
		var day = d.getDate();
	}
	
	var weekday=new Array("Sun", "Mon", "Tue", "Wed", "Thur", "Fri", "Sat");
	
	var month=new Array("Jan", "Feb", "Mar", "Apr", "May", "June", "July", "Aug", "Sept", "Oct", "Nov", "Dec");
	
	document.getElementById("TimeUpdate").innerHTML= weekday[d.getDay()] + ", " + day + " " + month[d.getMonth()] + " " + d.getFullYear() + " - " + hours + ":" + mins + ":" + seconds + " GMT";
	setTimeout("Time()",1000);
}
setTimeout("Time()",10);

Google again. See the "getUTCxxx" methods. You are almost in business!

Next topic: that's very nice code. Clean, readable and not likely to ever be a source of bugs. Couple suggestions:

1) Don't concat "getElementById" with other operations. Better:

foo = document.getElementById( ... );
foo.innerHTML = ...;

2) Use an inner function:

function zero_pad( str ) {
if (str.length === 1) { return '0' + str; }
else { return str; }
}

You put the inner function right inside the one you've got:

function your_func( ... ) {

...
function zero_pad( str ) { ... }
}

And you use it like so:

function your_func( ... ) {

...
var day1 = zero_pad( getUTCxxx(...) );

function zero_pad( str ) { ... }

}

JavaScript is great and inner functions are one of the things that make it great.

Martin

Seems this board loses indents if you don't use CODE tags. Ugh. Imagine my indents.

Thanks for your reply MartinRinehart!

Google again. See the "getUTCxxx" methods. You are almost in business!

I have seen the getUTC methods, however they get the UTC time which isnt always the same as GMT time because of daylight saving.

Also, thanks for the suggestions.

Anyone else have any ideas?

If you want the time zone, use getTimezoneOffset() to obtain the number of minutes difference. Then you just manipulate with your current local datetime? You can google for getTimezoneOffset() and javascript to see how it is used.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.