Adding UTC time to my countdown timer - javascript

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

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

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

Check if time difference is less than 45 mins and if time is past current time - AngularJS

This is an easy thing to do in PHP with code like this;
if (strtotime($given_time) >= time()+300) echo "You are online";
But can't find anything on SO to do exactly this in javascript.
I want to check if the difference between a given time and the current time is less than 45mins
For instance
$scope.given_time = "14:10:00"
$scope.current_time = new Date();
I'm only concerned with the time part. I need to extract time part from new Date(); and then compare.
Then this should be true
How can I achieve this with Javascript:
if ($scope.given_time - $scope.current_time < 45 minutes && if $scope.given_time > time()) {
// do something
}
The below function provided by #Pete solves the first part (45mins part)
function checkTime(time) {
var date = new Date();
var date1 = new Date((date.getMonth() + 1) + "/" + date.getDate() + "/" + date.getFullYear() + " " + time);
var minutes = (date1.getTime() - date.getTime()) / (60 * 1000);
if (minutes > 45 || (minutes < 0 && minutes > -1395)) {
// greater than 45 is todays time is above 45 minutes
// less than 0 means the next available time will be tomorrow and the greater than -1395 means it will be more than 45 minutes from now into tomorrow
document.write(time + ': true<br />');
} else {
document.write(time + ': false<br />');
}
}
Subtracting two date objects results in difference in milliseconds. So compare that to the number of milliseconds in 45 minutes.
var date1 = new Date();
var date2 = new Date();
date2.setTime(date2.getTime() + (50 * 60 * 1000)); //adding 50 minutes just to see console message
if (date2-date1 >= 45*60*1000) {
console.log("greater than 45 minutes");
}
compare it with timestamps. IMO this is the easiest way. I don't know what this has to do with angularJs.
var currentTimeStamp = new Date().getTime(); //timestamp in ms
var beforeTimeStamp = startDate.getTime(); //timestamp in ms
if (currentTimeStamp - beforeTimeStamp < 45*60*1000 && currentTimeStamp - beforeTimeStamp > 0) {
//do smth
}
note that startDate is the Date which was created by logging in for example.

show server time including timezone offset

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

Javascript countdown using server-side time to complete

I am using this script to countdown and it works.
<script type="text/javascript">
(function (e) {
e.fn.countdown = function (t, n) {
function i() {
eventDate = Date.parse(r.date) / 1e3;
currentDate = Math.floor(e.now() / 1e3);
if (eventDate <= currentDate) {
n.call(this);
clearInterval(interval)
}
seconds = eventDate - currentDate;
days = Math.floor(seconds / 86400);
seconds -= days * 60 * 60 * 24;
hours = Math.floor(seconds / 3600);
seconds -= hours * 60 * 60;
minutes = Math.floor(seconds / 60);
seconds -= minutes * 60;
days == 1 ? thisEl.find(".timeRefDays").text("day") : thisEl.find(".timeRefDays").text("day");
hours == 1 ? thisEl.find(".timeRefHours").text("hours") : thisEl.find(".timeRefHours").text("hours");
minutes == 1 ? thisEl.find(".timeRefMinutes").text("Minutes") : thisEl.find(".timeRefMinutes").text("Minutes");
seconds == 1 ? thisEl.find(".timeRefSeconds").text("Seconds") : thisEl.find(".timeRefSeconds").text("Seconds");
if (r["format"] == "on") {
days = String(days).length >= 2 ? days : "0" + days;
hours = String(hours).length >= 2 ? hours : "0" + hours;
minutes = String(minutes).length >= 2 ? minutes : "0" + minutes;
seconds = String(seconds).length >= 2 ? seconds : "0" + seconds
}
if (!isNaN(eventDate)) {
thisEl.find(".days").text(days);
thisEl.find(".hours").text(hours);
thisEl.find(".minutes").text(minutes);
thisEl.find(".seconds").text(seconds)
} else {
alert("Invalid date. Example: 30 Tuesday 2013 15:50:00");
clearInterval(interval)
}
}
thisEl = e(this);
var r = {
date: null,
format: null
};
t && e.extend(r, t);
i();
interval = setInterval(i, 1e3)
}
})(jQuery);
$(document).ready(function () {
function e() {
var e = new Date;
e.setDate(e.getDate() + 60);
dd = e.getDate();
mm = e.getMonth() + 1;
y = e.getFullYear();
futureFormattedDate = mm + "/" + dd + "/" + y;
return futureFormattedDate
}
$("#countdown").countdown({
date: "<?php echo $newcounter ?> ", // Change this to your desired date to countdown to
format: "on"
});
});
</script>
This script uses my client date, but i want use my server date. How can read the date read from my server? I tried this code in my script:
currentDate = <?php echo time() ?>;
but my countdown stops and does not work.
You have the server time. You are going about this correctly - no need to use AJAX. I think your problem involves the format of the date you ae passing to the countdown function. The countdown appears to want a number (newcounter = number milliseconds to wait?), but you are passing a timestamp (<?php echo time() ?>).
See #APAD1 comment above.
<?php
date_default_timezone_set('Europe/Vienna');
$now = new DateTime();
$dateJsFormat = $now->format('Y') .',' . ($now->format('m')-1) .','.$now->format('d') .',' . $now->format('H') .','.$now->format('i');
?>
<script>
var date = new Date(<?= $dateJsFormat ?>);
alert(date);
</script>
The JS-Date Object expects this format as parameters:
new Date(Year, Month, day, hour, minute) // JS-Code
The Month must be decremented by 1:
$now->format('m')-1 // see php-code above
In your example, you have to set this:
$("#countdown").countdown({
date: "<?= dateJsFormat ?>", // Change this to your desired date to countdown to
format: "on"
});
Hope this helps.

Categories