show server time including timezone offset - javascript

i have some difficulties showing the actual time of the server using php and js.
on the server-side i have following php code:
$date = new DateTime();
echo $date->getTimestamp();
on the client-side if have the following js code that changes the content of a div to display the current time:
flag = true;
timer = '';
function clock()
{
if ( flag ) {
xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", "backend/time_backend.php?action=serverTime", false);
xmlhttp.send();
var stamp = xmlhttp.responseText;
timer = stamp*1000;
}
var d = new Date(timer);
var hours = d.getHours();
var minutes = d.getMinutes();
var seconds = d.getSeconds();
//hours = hours % 12;
//hours = hours ? hours : 12; // the hour ’0' should be ’12'
minutes = minutes < 10 ? '0'+minutes : minutes;
seconds = seconds < 10 ? '0'+seconds : seconds;
var strTime = hours + ':' + minutes + ':' + seconds;
document.getElementById("clock").innerHTML= strTime ;
flag = false;
timer = timer + 1000;
}
window.onload = function() {
setInterval(clock, 1000);
};
this works as long as the timezone of the server and mine are the same. but as soon as i change the timezone on the server, it doesn't work anymore. it still will show my local client time although the bash command date on the server shows the time in the right offset.
how do i fix this? i really need to show the server-local time.

You are sending in unix timestamp from PHP
must be probably using
echo date("Y-m-d H:i:s", time());
if you want to use the string for creating date object using JS.
Your JS code should be
function clock()
{
if ( flag ) {
xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", "backend/time_backend.php?action=serverTime", false);
xmlhttp.send();
var stamp = xmlhttp.responseText;
var timer = new Date(stamp);
}
var d = new Date(timer);
var hours = d.getHours();
var minutes = d.getMinutes();
var seconds = d.getSeconds();
//hours = hours % 12;
//hours = hours ? hours : 12; // the hour ’0' should be ’12'
minutes = minutes < 10 ? '0'+minutes : minutes;
seconds = seconds < 10 ? '0'+seconds : seconds;
var strTime = hours + ':' + minutes + ':' + seconds;
document.getElementById("clock").innerHTML= strTime ;
flag = false;
timer = new Date(timer.getTime() + 1000);
}

You could use an ISO 8601 formatted date.
$date = date("c", time());
Will give you one.
ISO 8601 Data elements and interchange formats – Information
interchange – Representation of dates and times is an international
standard covering the exchange of date and time-related data. It was
issued by the International Organization for Standardization (ISO) and
was first published in 1988. The purpose of this standard is to
provide an unambiguous and well-defined method of representing dates
and times, so as to avoid misinterpretation of numeric representations
of dates and times, particularly when data are transferred between
countries with different conventions for writing numeric dates and
times.
You could then do Date.parse() in which will return a timestamp ;) then proceed as if you received a timestamp.

Date::getTimestamp always returns the Unix timestamp. Unix timestamp does not store time zone information.
Solution is to build the JavaScript Date object from the date information given by the server.
Note: The time will not go out of sync when server or the client changes time zones (i.e. DST). If avoiding requests to backend a more accurate solution would be to use a time zone library in JavaScript (e.g. timezone.js).
PHP:
$date = new DateTime;
echo json_encode(array(
'year' => (int) $date->format('Y'),
'month' => (int) $date->format('m'),
'day' => (int) $date->format('j'),
'hours' => (int) $date->format('H'),
'minutes' => (int) $date->format('i'),
'seconds' => (int) $date->format('s'),
));
JavaScript:
var date = null;
function updateTime() {
if (!date) {
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", "backend/time_backend.php?action=serverTime", false);
xmlhttp.send();
var j = JSON.parse(xmlhttp.responseText);
date = new Date(
j['year'], j['month'],
j['day'], j['hours'],
j['minutes'], j['seconds']
);
return;
}
// Increment time by 1 second
date.setTime(date.getTime() + 1000);
}
function clock() {
updateTime();
var hours = date.getHours();
var minutes = date.getMinutes();
var seconds = date.getSeconds();
hours = hours % 12;
hours = hours ? hours : 12; // the hour ’0' should be ’12'
minutes = minutes < 10 ? '0'+minutes : minutes;
seconds = seconds < 10 ? '0'+seconds : seconds;
var strTime = hours + ':' + minutes + ':' + seconds;
document.getElementById('clock').innerHTML = strTime;
}
window.onload = function() {
setInterval(clock, 1000);
};

Related

Put clock forward by one hour [duplicate]

It amazes me that JavaScript's Date object does not implement an add function of any kind.
I simply want a function that can do this:
var now = Date.now();
var fourHoursLater = now.addHours(4);
function Date.prototype.addHours(h) {
// How do I implement this?
}
I would simply like some pointers in a direction.
Do I need to do string parsing?
Can I use setTime?
How about milliseconds?
Like this:
new Date(milliseconds + 4*3600*1000 /* 4 hours in ms */)?
This seems really hackish though - and does it even work?
JavaScript itself has terrible Date/Time API's. Nonetheless, you can do this in pure JavaScript:
Date.prototype.addHours = function(h) {
this.setTime(this.getTime() + (h*60*60*1000));
return this;
}
Date.prototype.addHours= function(h){
this.setHours(this.getHours()+h);
return this;
}
Test:
alert(new Date().addHours(4));
The below code will add 4 hours to a date (example, today's date):
var today = new Date();
today.setHours(today.getHours() + 4);
It will not cause an error if you try to add 4 to 23 (see the documentation):
If a parameter you specify is outside of the expected range, setHours() attempts to update the date information in the Date object accordingly
It is probably better to make the addHours method immutable by returning a copy of the Date object rather than mutating its parameter.
Date.prototype.addHours= function(h){
var copiedDate = new Date(this.getTime());
copiedDate.setHours(copiedDate.getHours()+h);
return copiedDate;
}
This way you can chain a bunch of method calls without worrying about state.
The version suggested by kennebec will fail when changing to or from DST, since it is the hour number that is set.
this.setUTCHours(this.getUTCHours()+h);
will add h hours to this independent of time system peculiarities.
Jason Harwig's method works as well.
Get a date exactly two hours from now, in one line.
You need to pass milliseconds to new Date.
let expiryDate = new Date(new Date().setHours(new Date().getHours() + 2));
or
let expiryDate2 = new Date(Date.now() + 2 * (60 * 60 * 1000) );
let nowDate = new Date();
let expiryDate = new Date(new Date().setHours(new Date().getHours() + 2));
let expiryDate2 = new Date(Date.now() + 2 * (60 * 60 * 1000) );
console.log('now', nowDate);
console.log('expiry', expiryDate);
console.log('expiry 2', expiryDate2);
You can use the Moment.js library.
var moment = require('moment');
foo = new moment(something).add(10, 'm').toDate();
I also think the original object should not be modified. So to save future manpower here's a combined solution based on Jason Harwig's and Tahir Hasan answers:
Date.prototype.addHours= function(h){
var copiedDate = new Date();
copiedDate.setTime(this.getTime() + (h*60*60*1000));
return copiedDate;
}
If you would like to do it in a more functional way (immutability) I would return a new date object instead of modifying the existing and I wouldn't alter the prototype but create a standalone function. Here is the example:
//JS
function addHoursToDate(date, hours) {
return new Date(new Date(date).setHours(date.getHours() + hours));
}
//TS
function addHoursToDate(date: Date, hours: number): Date {
return new Date(new Date(date).setHours(date.getHours() + hours));
}
let myDate = new Date();
console.log(myDate)
console.log(addHoursToDate(myDate,2))
There is an add in the Datejs library.
And here are the JavaScript date methods. kennebec wisely mentioned getHours() and setHours();
Check if it’s not already defined. Otherwise, define it in the Date prototype:
if (!Date.prototype.addHours) {
Date.prototype.addHours = function(h) {
this.setHours(this.getHours() + h);
return this;
};
}
This is an easy way to get an incremented or decremented data value.
const date = new Date()
const inc = 1000 * 60 * 60 // an hour
const dec = (1000 * 60 * 60) * -1 // an hour
const _date = new Date(date)
return new Date(_date.getTime() + inc)
return new Date(_date.getTime() + dec)
Another way to handle this is to convert the date to unixtime (epoch), then add the equivalent in (milli)seconds, then convert it back. This way you can handle day and month transitions, like adding 4 hours to 21, which should result in the next day, 01:00.
SPRBRN is correct. In order to account for the beginning/end of the month and year, you need to convert to Epoch and back.
Here's how you do that:
var milliseconds = 0; //amount of time from current date/time
var sec = 0; //(+): future
var min = 0; //(-): past
var hours = 2;
var days = 0;
var startDate = new Date(); //start date in local time (we'll use current time as an example)
var time = startDate.getTime(); //convert to milliseconds since epoch
//add time difference
var newTime = time + milliseconds + (1000*sec) + (1000*60*min) + (1000*60*60*hrs) + (1000*60*60*24*days);
var newDate = new Date(newTime); //convert back to date; in this example: 2 hours from right now
Or do it in one line (where variable names are the same as above:
var newDate =
new Date(startDate.getTime() + millisecond +
1000 * (sec + 60 * (min + 60 * (hours + 24 * days))));
For a simple add/subtract hour/minute function in JavaScript, try this:
function getTime (addHour, addMin){
addHour = (addHour ? addHour : 0);
addMin = (addMin ? addMin : 0);
var time = new Date(new Date().getTime());
var AM = true;
var ndble = 0;
var hours, newHour, overHour, newMin, overMin;
// Change form 24 to 12 hour clock
if(time.getHours() >= 13){
hours = time.getHours() - 12;
AM = (hours>=12 ? true : false);
}else{
hours = time.getHours();
AM = (hours>=12 ? false : true);
}
// Get the current minutes
var minutes = time.getMinutes();
// Set minute
if((minutes + addMin) >= 60 || (minutes + addMin) < 0){
overMin = (minutes + addMin) % 60;
overHour = Math.floor((minutes + addMin - Math.abs(overMin))/60);
if(overMin < 0){
overMin = overMin + 60;
overHour = overHour-Math.floor(overMin/60);
}
newMin = String((overMin<10 ? '0' : '') + overMin);
addHour = addHour + overHour;
}else{
newMin = minutes + addMin;
newMin = String((newMin<10 ? '0' : '') + newMin);
}
// Set hour
if((hours + addHour >= 13) || (hours + addHour <= 0)){
overHour = (hours + addHour) % 12;
ndble = Math.floor(Math.abs((hours + addHour)/12));
if(overHour <= 0){
newHour = overHour + 12;
if(overHour == 0){
ndble++;
}
}else{
if(overHour == 0){
newHour = 12;
ndble++;
}else{
ndble++;
newHour = overHour;
}
}
newHour = (newHour<10 ? '0' : '') + String(newHour);
AM = ((ndble + 1) % 2 === 0) ? AM : !AM;
}else{
AM = (hours + addHour == 12 ? !AM : AM);
newHour = String((Number(hours) + addHour < 10 ? '0': '') + (hours + addHour));
}
var am = (AM) ? 'AM' : 'PM';
return new Array(newHour, newMin, am);
};
This can be used without parameters to get the current time:
getTime();
Or with parameters to get the time with the added minutes/hours:
getTime(1, 30); // Adds 1.5 hours to current time
getTime(2); // Adds 2 hours to current time
getTime(0, 120); // Same as above
Even negative time works:
getTime(-1, -30); // Subtracts 1.5 hours from current time
This function returns an array of:
array([Hour], [Minute], [Meridian])
If you need it as a string, for example:
var defaultTime: new Date().getHours() + 1 + ":" + new Date().getMinutes();
I think this should do the trick
var nextHour = Date.now() + 1000 * 60 * 60;
console.log(nextHour)
You can even format the date in desired format using the moment function after adding 2 hours.
var time = moment(new Date(new Date().setHours(new Date().getHours() + 2))).format("YYYY-MM-DD");
console.log(time);
A little messy, but it works!
Given a date format like this: 2019-04-03T15:58
//Get the start date.
var start = $("#start_date").val();
//Split the date and time.
var startarray = start.split("T");
var date = startarray[0];
var time = startarray[1];
//Split the hours and minutes.
var timearray = time.split(":");
var hour = timearray[0];
var minute = timearray[1];
//Add an hour to the hour.
hour++;
//$("#end_date").val = start;
$("#end_date").val(""+date+"T"+hour+":"+minute+"");
Your output would be: 2019-04-03T16:58
The easiest way to do it is:
var d = new Date();
d = new Date(d.setHours(d.getHours() + 2));
It will add 2 hours to the current time.
The value of d = Sat Jan 30 2021 23:41:43 GMT+0500 (Pakistan Standard Time).
The value of d after adding 2 hours = Sun Jan 31 2021 01:41:43 GMT+0500 (Pakistan Standard Time).

jonthornton timepicker : How to get hours and minues

I'm using the jonthornton/jquery-timepicker and could not find the hours and minutes selected.
All I could find was a string output of the form '10:30pm'.
Can the hours and minutes be accessed directly from the control?
I imagined you would be able to do this but could not find it.
The best I've been able to do is what follows, anyone got anything better?
$('#StartTime').on('change', function (timeControl) {
var hoursString;
if (timeControl.target.value.indexOf("am") >= 0) {
hoursString = timeControl.target.value.replace("am", ":00 AM");
}
else {
hoursString = timeControl.target.value.replace("pm", ":00 PM");
}
var oneDate = new Date(Date.parse("2000-01-01 " + hoursString));
var minutes = oneDate.getMinutes();
var hours = oneDate.getHours();
console.log("Hours : " + hours + " | Minutes : " + minutes);
});
The long-standing answer would be Moment.js but it is now considered a legacy project in maintenance mode and not recommended for new projects. There are recommendations on their website for replacements, but bringing in a new dependency for this may be overkill.
The value coming in seems to follow a format which we can rely on to make parsing easy.
Format: H:MMxx
Key:
H = hour, 1-2 characters
MM = minutes, always 2 characters
xx = am or pm, always 2 characters
var timeArray = timeControl.split(':');
var meridiem = timeArray[1].substring(2, 4);
var hours = parseInt(timeArray[0]) + (meridiem === 'pm' ? 12 : 0);
var minutes = parseInt(timeArray[1].substring(0, 2));
var seconds = 0;
// Local time zone, read more: https://stackoverflow.com/a/29297375/5988852
var date = new Date();
date.setHours(hours, minutes, seconds);
// If you want UTC instead
utc = Date.UTC(
date.getUTCFullYear(),
date.getUTCMonth(),
date.getUTCDate(),
hours,
minutes,
seconds
);
var date = new Date(utc);

How to get servers time

Okay so i need a countdown to the servers midnight because when the server reach midnight it will run a cronjob which is relevant to the users so they need to see how many hours that are left untill it is midnight on the server and not in their own timezone.
Sample page here
The date_default_timezone_get(); is europe/copenhagen
PHP
(The page the Ajax is requesting)
echo time() * 1000;
Javascript
(function () {
var test = document.getElementById("test");
var difference = document.getElementById("difference");
var serverMilli = document.getElementById("serverMilli");
var serverCountdown = document.getElementById("serverCountdown");
var machineMilli = document.getElementById("machineMilli");
var machineCountdown = document.getElementById("machineCountdown");
let serverTime;
var localTime;
var http = new XMLHttpRequest();
var url = "time.php";
http.open("POST", url, true);
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.onreadystatechange = function () {
if (http.readyState === 4 && http.status === 200) {
serverTime = this.responseText;
}
;
};
http.send();
function countDownServer() {
var now = new Date();
var localTime = now.getTime();
var currentDiff = serverTime - localTime;
var currentTest = serverTime - currentDiff;
var currentTime = currentTest;
var eventDate = new Date();
eventDate.setDate(now.getDate() + 1);
eventDate.setHours(24);
eventDate.setMinutes(0);
eventDate.setSeconds(0);
eventDate.setMilliseconds(0);
var eventTime = eventDate.getTime();
var remainingTime = eventTime - currentTime;
var sekunder = Math.floor(remainingTime / 1000);
var minutter = Math.floor(sekunder / 60);
var timer = Math.floor(minutter / 60);
sekunder %= 60;
minutter %= 60;
timer %= 24;
sekunder = (sekunder < 10) ? "0" + sekunder : sekunder;
minutter = (minutter < 10) ? "0" + minutter : minutter;
timer = (timer < 10) ? "0" + timer : timer;
var testServer = timer + ":" + minutter + ":" + sekunder;
serverCountdown.textContent = testServer;
setTimeout(countDownServer, 1000);
}
countDownServer();
})();
Everything "kinda" works... the problem is if i change the timezone on my computer it will display longer hours untill midnight than it really is on the server?
How is this possible when the timezone on server is europe/copenhagen and i use time() ? should it not use the servers timezone?
No as javascript executes in your browser, it will use the timezone of your computer.
You have to tell javascript which timezone you would like (if not your one)
I found this for you:
How to get Time of specific timezone using javascript?
The JavaScript Date object always uses the user's computer time. You can use a library like Moment Timezone to set a different timezone that can be calculated on the client.
Otherwise you can try and calculate the difference between the server time and local time, but it might be off by an hour a couple times per year due to differences in DST.

How to add minutes and hours to a time string using jquery

I want to add 30 minutes and then one hour to my variable which i already have my own date
var initialDate = '10:00';
So
if (some condition){
// i add 30 minutes ->10:30
}elseif(another condition){
// i add 1hour ->11:00
}
I tried this but doesn't work
var initialDate = '10:00';
var theAdd = new Date(initialDate);
var finalDate = theAdd.setMinutes(theAdd.getMinutes() + 30);
If I understand you correctly, the following will help you.
You need to add momentjs dependency via script tag and you can Parse, validate, manipulate, and display dates in JavaScript.
You can find more documentation regarding this in momentjs website
console.log(moment.utc('10:00','hh:mm').add(1,'hour').format('hh:mm'));
console.log(moment.utc('10:00','hh:mm').add(30,'minutes').format('hh:mm'));
<script src="https://momentjs.com/downloads/moment-with-locales.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
var theAdd = new Date();
// Set Hours, minutes, secons and miliseconds
theAdd.setHours(10, 00, 00, 000);
if (some condition) {
// add 30 minutes --> 10:30
theAdd.setMinutes(theAdd.getMinutes() + 30);
}
elseif (some condition) {
// add 1 hour --> 11:00
theAdd.setHours(theAdd.getHours() + 1);
}
Then you print the var theAdd to obtain the date and time.
To obtain just the time:
theAdd.getHours() + ":" + theAdd.getMinutes();
This should do the job. Dates need a year and month in their constructor, and you have to specify larger units of time if you specify and smaller ones, so it needs a day as well. Also, you have to pass in the hours and minutes separately. See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date.
var initialDate = '10:00';
var theAdd = new Date(1900,0,1,initialDate.split(":")[0],initialDate.split(":")[1]);
if(30 min condition){
theAdd.setMinutes(theAdd.getMinutes() + 30);
} else if (1 hour condition){
theAdd.setHours(theAdd.getHours() + 1);
}
console.log(theAdd.getHours()+":"+theAdd.getMinutes());
Here is a javascript function that will add minutes to hh:mm time string.
function addMinutes(timeString, addMinutes) {
if (!timeString.match(/^([0-9]|0[0-9]|1[0-9]|2[0-3]):[0-5][0-9]$/))
return null;
var timeSplit = timeString.split(':');
var hours = parseInt(timeSplit[0]);
var minutes = parseInt(timeSplit[1]) + parseInt(addMinutes);
hours += Math.floor(minutes / 60);
while (hours >= 24) {
hours -= 24;
}
minutes = minutes % 60;
return ('0' + hours).slice(-2) + ':' + ('0' +minutes).slice(-2);
}

Adding UTC time to my countdown timer

I recently was searching after a countdown script that count down to a specific day, hour and minute and reset again after it reached the time.
Now a week later i see a major issue in the script. The countdown is based on local time and this is a problem.
I want to have the countdown based on the UTC time and not the local pc time.
Anyone that can help me with this because i'm not sure how to do this. I made also a clock script that i use and there i could say ".getUTC..." but i have no idea how to implement that in this script because i picked it up from the internet.
I'm not very good in javascript/jquery and i'm still learning a lot. I can mostely understand the scripts but i miss the lack of writing it myself so it would be very nice if you could edit the script so it's based on the UTC time and tell me a bit about it so i can learn from it. I really would appriciate that !
Thanks a lot,
Jens
var EVENTDAY = 1; // monday
var EVENTHOUR = 22; //
var EVENTMINUTE = 42; //
function getRemaining( now )
{
if ( now == null ) now = new Date();
var dow = now.getDay();
// the "hour" for now must include fractional parts of the hour, so...
var hour = now.getHours() + now.getMinutes()/60 + now.getSeconds()/3600;
// how many days from current day until event day?
var offset = EVENTDAY - dow;
// if event day is past *OR* if today is the event day but the event time is past...
if ( offset < 0 || ( offset == 0 && EVENTHOUR < hour ) )
{
// we are past the event time in current week, so
// target EVENTDAY is next week:
offset += 7;
}
// so this date (day of the month) is the next occurrence of the event:
var eventDate = now.getDate() + offset;
// and so then next occurrence of the event is at this time:
var eventTime = new Date( now.getFullYear(), now.getMonth(), eventDate,
EVENTHOUR, EVENTMINUTE, 0 );
// this is how many milliseconds from now to the next event occurrence
var millis = eventTime.getTime() - now.getTime();
// convert milliseconds to days/hours/minutes/seconds:
var seconds = Math.round( millis / 1000 );
var minutes = Math.floor( seconds / 60 );
seconds %= 60;
var hours = Math.floor( minutes / 60);
minutes %= 60;
var days = Math.floor( hours / 24 );
hours %= 24;
if ( seconds < 10 ) seconds = "0" + seconds;
if ( minutes < 10 ) minutes = "0" + minutes;
if ( hours < 10 ) hours = "0" + hours;
if ( days == 1 ) {
days = days + " day, ";
}
else {
days = days + " days, ";
}
// and return that formatted pretty:
return days + hours + ":" + minutes + ":" + seconds;
}
function tick()
{
// this is the automatic once a second display:
document.getElementById("countdown").innerHTML = getRemaining();
}
setInterval( tick, 1000 ); // specifies once a second
// here is a demo that allows you to test the function
// by specifying a date and time in the <form> below
function demo( form )
{
var t = form.theDate.value.split("/");
var mn = Number(t[0]);
var dy = Number(t[1]);
var yr = Number(t[2]);
var t = form.theTime.value.split(":");
var hr = Number(t[0]);
var mi = Number(t[1]);
var sc = Number(t[2]);
// so this is the test date/time that you specified:
var test = new Date( yr, mn-1, dy, hr, mi, sc );
// and here we call the master function and put its answer in the <form>:
form.remaining.value = getRemaining( test );
}
using Jcounter
Change line 34 in the jquery.jCounter-0.1.4.js file
serverDateSource: '/pathtofile/dateandtime.php', //path to dateandtime.php file (i.e. http://my-domain.com/dateandtime.php)
in the dateandtime.php file
<?php
ini_set('display_errors', 0); error_reporting(E_ALL);
date_default_timezone_set("Pacific/Auckland"); // CHANGE HERE
// GMT +12
if (isset($_GET['timezone'])) {
$timezone = new DateTimeZone($_GET['timezone']);
} else {
$timezone = new DateTimeZone("Pacific/Auckland");//CHANGE HERE
}
$date = new DateTime();
$date->setTimezone($timezone);
$dateAndTime = array("currentDate"=>$date->format('d F Y H:i:s'));
echo $_GET['callback'] . '(' . json_encode($dateAndTime) . ')';
?>
Then in you countdown timer file have it setup something like this:
<?php
date_default_timezone_set("Pacific/Auckland");//GMT+12 <--- CHANGE THIS
//Set your date and time below.
$day = date("D");
$hour = date("H");
if ($day=="Sun" && $hour>='9') {$date = date('d F Y H:i:s', strtotime('next Sunday 09:00:00'));}
else {$date = date('d F Y H:i:s', strtotime('this Sunday 09:00:00'));}
?>
<script type="text/javascript">
$(document).ready(function() {
$(".mycountdownname").jCounter({
animation: "slide",
date: "<?=$date?>", //format: DD month YYYY HH:MM:SS
timezone: "Pacific/Auckland",
format: "dd:hh:mm:ss",
twoDigits: 'on',
callback: function() { console.log("Event Ended!") }
});
});
</script>
<div class="mycountdownname">
<div class="countdown-theme">
<ul>
<li><p><span><em><b class="days">00</b><i class="daysSlider"><u>00</u><u>00</u></i></em>DAYS</span></p></li>
<li><p><span><em><b class="hours">00</b><i class="hoursSlider"><u>00</u><u>00</u></i></em>HOURS</span></p></li>
<li><p><span><em><b class="minutes">00</b><i class="minutesSlider"><u>00</u><u>00</u></i></em>MINS</span></p></li>
<li><p><span><em><b class="seconds">00</b><i class="secondsSlider"><u>00</u><u>00</u></i></em>SECS</span></p></li>
</ul>
<div class="jC-clear"></div><br>
<div class="jC-clear"></div>
</div>
</div>
You are already using Date here:
if ( now == null ) now = new Date();
You are almost there. Let's see some useful functions.
new Date().getTime()
will return the utc time.
new Date().toUTCString()
returns a string representation of the UTC timestamp.
new Date().getTimezoneOffset()
returns the number of minutes to be added to get the UTC value. So, this is how you can get the UTC timestamp:
foo.setHours(foo.getHours() + (foo.getTimezoneOffset() / 60)).getTimezoneOffset()
where foo is a Date object.
So, this is how you get the UTC value of a date:
function getUTCDate(input) {
return input.setHours(input.getHours() + (input.getTimezoneOffset() / 60)).getTimezoneOffset();
}
This is how you use it:
var now = getUTCDate(new Date());

Categories