JQuery and PHP Date difference - php

I am using a jquery date picker and also setting a date through php date('Y-m-D') functions. Both of them give different date for today. Jquery picker fills the field with the date that is one day ahead of php date(). Here is the function for jquery. I need jquery to show same date for today as php.
<script type="text/javascript" charset="utf-8">
var $j = jQuery.noConflict();
$j(function()
{
// initialise the "Select date" link
$j('#date-pick')
.datePicker(
// associate the link with a date picker
{
createButton:false,
startDate: '01/01/1970',
endDate: (new Date()).asString()
//endDate:<?php echo date('y-m-d'); ?>
}
).bind(
// when the link is clicked display the date picker
'click',
function()
{
updateSelects($j(this).dpGetSelected()[0]);
$j(this).dpDisplay();
return false;
}
).bind(
// when a date is selected update the SELECTs
'dateSelected',
function(e, selectedDate, $td, state)
{
updateSelects(selectedDate);
}
).bind(
'dpClosed',
function(e, selected)
{
updateSelects(selected[0]);
}
).val(new Date().asString()).trigger('change');
var updateSelects = function (selectedDate)
{
var selectedDate = new Date(selectedDate);
if(selectedDate != "Invalid Date")
{
$j('#d').val(selectedDate.getDate());
$j('#m').val(selectedDate.getMonth()+1);
$j('#y').val(selectedDate.getFullYear());
}
}
// listen for when the selects are changed and update the picker
// default the position of the selects to today
var today = new Date();
updateSelects(today.getTime());
});
</script>

jQuery uses the client computer's date while php uses the server's date. They're basically different if you haven't set the default timezone in php. Take a look at this:
http://php.net/manual/en/function.date-default-timezone-set.php
You can set the default timezone in php.ini file located on the PHP main directory (Eg. PHP5.4)
As for the using of the server's date in the datepicker:
A quick google search lead me to this: how to display server side dates in jquery datepicker?
basically what they have done is creating a new date based on the current timestamp:
$timestamp = strtotime("2012-08-02");
minDate: new Date('<?php echo $timestamp; ?>');

DO NOT TRUST THE CLIENTS DATE AND TIME
These values can be altered at a whim.
Just use them on advisement.
Besides Javascript is there to enhance the users experience (i.e. make it more interactive). But at the end of the day you will have to pick up the pieces it you do not validate and verify the data you get from the client

Related

How do I find user timezone in php?

How can I dynamically find user timezone in config.php file in codeigniter?
date_default_timezone_set('Asia/Kolkata');
You must either use javascript (for example http://momentjs.com/timezone/) or then you must use the geoip to determine it in the backend side (CURL the client ip to http://freegeoip.net/?q=IP_ADDR). Also if you have multiple TLDs (for example .com, .se etc.) you can use those if nothing else works. Of course you should allow the user to change the timezone from user interface in case the automatic way fails for some reason.
Using Javascript you can get the user timezone:
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js">
</script>
<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/jstimezonedetect/1.0.4/jstz.min.js">
</script>
<script type="text/javascript">
$(document).ready(function(){
var tz = jstz.determine(); // Determines the time zone of the browser client
var timezone = tz.name(); //'Asia/Kolhata' for Indian Time.
document.getElementById("hiddenVal").value = timezone;
</script>
After getting timezone in javascript you can use that value in php code.
In HTML make an hidden element with name and id as "hiddenval" and get value from that element on form submit like
<?hpp
echo$usertime_zone = $_REQUEST['hiddenval'];
?>
In case if you only want to use PHP then utilize the following code:
<?php
$ip = $_SERVER['REMOTE_ADDR']; // means we got user's IP address
$json = file_get_contents( 'http://smart-ip.net/geoip-json/' . $ip); // this one service we gonna use to obtain timezone by IP
// maybe it's good to add some checks (if/else you've got an answer and if json could be decoded, etc.)
$ipData = json_decode( $json, true);
if ($ipData['timezone']) {
$tz = new DateTimeZone( $ipData['timezone']);
$now = new DateTime( 'now', $tz); // DateTime object corellated to user's timezone
} else {
// we can't determine a timezone - do something else...
}
<?php
session_start();
$timezone = $_SESSION['time'];
?>
This will read the session variable "time", which we are now about to create.
On the same page, in the <head> section, first of all you need to include jQuery:
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
Also in the <head> section, paste this jQuery:
<script type="text/javascript">
$(document).ready(function() {
if("<?php echo $timezone; ?>".length==0){
var visitortime = new Date();
var visitortimezone = "GMT " + -visitortime.getTimezoneOffset()/60;
$.ajax({
type: "GET",
url: "http://domain.com/timezone.php",
data: 'time='+ visitortimezone,
success: function(){
location.reload();
}
});
}
});
</script>
You may or may not have noticed, but you need to change the url to your actual domain.
One last thing. You are probably wondering what the heck timezone.php is. Well, it is simply this: (create a new file called timezone.php and point to it with the above url)
<?php
session_start();
$_SESSION['time'] = $_GET['time'];
?>
If this works correctly, it will first load the page, execute the JavaScript, and reload the page. You will then be able to read the $timezone variable and use it to your pleasure! It returns the current UTC/GMT time zone offset (GMT -7) or whatever timezone you are in.

jquery countdown changes when user change its system time

i'm using jquery countdown with php. i have given an end date which is going to the countdown. my problem is lets suppose 1 hour left is showing in countdown but when a user change its system time the countdown changes. like if a user back his time 1 hour then the counter will display the 2 hours left. is there any way to get the server time for more accurate time not the user system time. please help.
how can i get server time not user system time?
below is my jquery code
if($(pluginsArray[6]).length){
$(pluginsArray[6]).each(function(){
var $this = $(this),
dateObj = $this.data();
var finalDate = new Date(dateObj.year, dateObj.month, dateObj.day, dateObj.hours, dateObj.minutes);
$this.countdown({
timezone: +4,
until : finalDate,
expiryText: '<div class="over">Closed.</div>',
onExpiry : function(){
setTimeout(function( ) { location.reload(); }, 5000);
},
format :'DHMS',
layout : '<b>{dn}</b> <span class="fs_medium d_inline_b m_right_5">days</span> <b>{hn}</b> <span class="fs_medium d_inline_b m_right_5">hrs</span> <b>{mn}</b> <span class="fs_medium d_inline_b m_right_5">min</span> <b>{sn}</b> <span class="fs_medium">sec</span>'
});
});
}
and here is what i did in php
<div class="countdown color_redc d_inline_m fs_large second_font lh_small f_xs_20" style="font-size:26px;" data-year="<?= $aDate[0] ?>" data-month="<?= ($aDate[1] - 1) ?>" data-day="<?= $aDate[2] ?>" data-hours="<?= $aDate[3] ?>" data-minutes="<?= $aDate[4] ?>"></div>
Solution without PHP
What you can do, without coding any server side is using a public API to get current time.
Found a similar topic on StackoverFlow : Free Rest API to get current time as string (timezone irrelevant)
TimezoneDb provides a free API: http://timezonedb.com/api
GenoNames also has a RESTful API available to get the current time for
a given location: http://www.geonames.org/export/ws-overview.html.
You can use Greenwich, UK if you'd like GMT.
GenoNames looks to be US only, TimezoneDb works you just need to register for a free public key.
Few people recommend timeapi.org but looks like they do not accept CROSS-DOMAIN request in Ajax, and the exemple they provide is no longer available.
Solution with PHP and jQuery Countdown configuration
Also you can ask jQuery CountDown to synchronyze with your server using serverSync option
$(selector).countdown({
until:liftoffTime, serverSync: serverTime});
function serverTime() {
var time = null;
$.ajax({url: 'http://myserver.com/serverTime.php',
async: false, dataType: 'text',
success: function(text) {
time = new Date(text);
}, error: function(http, message, exc) {
time = new Date();
}});
return time;
}
PHP file : serverTime.php
<?php
$now = new DateTime();
echo $now->format("M j, Y H:i:s O")."\n";
?>
BUT
Keep in mind your user will always be able to change your code and fake it ... so if you need to implement some security this is not enough and you will need to code some backend stuff.

Date field is being reset in PHP and MySQL

When I am trying to edit some fields in the form, the date is being reset to 01-01-1970 01:00:00 but its stores and retrieves its value from the database perfectly for the very first time. Then it's being reset when I edit some other fields except date.
Below my jQuery date picker:
<script>
$(document).ready(function(){
$("#policy_start_date").datepicker({
numberOfMonths: 1,
onSelect: function(selected) {
$("#policy_end_date").datepicker("option","minDate", selected)
}
});
$("#policy_end_date").datepicker({
numberOfMonths: 1,
onSelect: function(selected) {
$("#policy_start_date").datepicker("option","maxDate", selected)
}
});
});
</script>
POST DATA
$date_t=$_POST['policy_start_date'];
$datearr=explode('/',$date_t);
$month=$datearr[0];
$day=$datearr[1];
$year=$datearr[2];
$policy_start_date=$year."-".$month."-".$day;
//$policy_end_date = $_POST['policy_end_date'];
$date_t=$_POST['policy_end_date'];
$datearr=explode('/',$date_t);
$month=$datearr[0];
$day=$datearr[1];
$year=$datearr[2];
$policy_end_date=$year."-".$month."-".$day;
Usually this is happen because the format stored in db and the format sent/acceptable by datepicker.
Standard datepicker format is 09/03/2013 (m/d/y).
What is displayed on the textbox when you echoed the data?
1. 09/03/2013 (m/d/y)
or
2. 2013-09-13 00:00:00 (Y-m-d H:i:s)
if option one (1) is displayed, then we certain need to see the code that display the form you used.
if option two(2) is displayed, then you need to format it before echoing into the textbox.
use this,
$time = strtotime($date_stored_in_database);
$your_date = date('Y/m/d',$time);
The strtotime will convert the date you stored in database into UNIX TIMESTAMP, and date function will convert it to the format you needed.

Retrieving and Comparing Dates using JQuery And PHP

I am using jQuery's datepicker in wordpress/PHP and I am using this code to show dates:
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script>
$(function() {
$("#datepicker").datepicker();
$("#datepicker").datepicker("option","dateFormat",'yy-mm-dd');
});
</script>
Date<input type="text" id="datepicker" size="20" maxlength="15" style="width: 80px;" readonly="readonly"/>
It successfully displays my date.
Also, I have a table (wp_redeem_vouchers) in the database that has specific voucher redemption dates saved in it:
id wp_deal_id redeem_date
1 Amazon6767 2012-03-21
2 Ebay87nm 2013-06-12
3 M&Svouc 2013-01-01
4 ASDA 2011-09-08
Question:
How can I retrieve "redeem_date" and compare with the datepicker's textbox date (upon selection) with the date already saved in the database?
Is there anyway I could disable past date so that user can't choose the past date from date picker? i.e The user on 14/03/2013 can't choose 22/02/2013 from datepicker.
For your i)
$('#datepicker').datepicker( {
minDate: 0,
onSelect: function(dateText, inst) {
$.ajax({
type: "POST",
url: "some.php",
data: { date: dateText },
onSuccess: function(e){
alert("success");
}
});
});
Then in the some.php file you do your compare with mysql and you return a success or failure getting the alert(success).
Then I would start with
$date = $_POST['date'];
die($date);
In the some.php just to see if it is passed correctly.
Well, you can pass your datepicker date string (adjust format to $("#datepicker").datepicker("option","dateFormat",'yyyy-mm-dd');) to following JavaScript function which creates a Date object:
function createDate(s) {
var bits = s.split('-');
var d = new Date(bits[0], bits[1] - 1, bits[2]);
return d;
}
Then you have to retrieve the date value from your database.
I do not know if there is a wordpress limitation but you can trigger a Ajax-Request which reads out the database value and give you as a response the date string as a JavaScript variable.
This variable can also be passed to the createDate(date) function. With these two date objects you can call easily compare the date with the time in milliseconds -> getTime() function of date object.
Regards

Jquery Countdown Server sync issue

I'm trying to create a countdown for an event. I'm using Jquery Countdown
I have this code:
$(function () {
var fecha = new Date("July 30, 2011 00:00:00");
$('#defaultCountdown').countdown({
until: fecha,
format: 'DHMS',
expiryUrl: "http://www.google.com",
serverSync: serverTime,
timezone: -4
});
});
function serverTime() {
var time = null;
$.ajax({
url: 'serverTime.php',
async: false,
dataType: 'text',
success: function (text) {
time = new Date(text);
},
error: function (http, message, exc) {
time = new Date();
}
});
return time;
}
The script is working fine, but when I try to change the clock date, the countdown changes.
Any idea why?
I imagine you created the serverTime.php file on your server?
http://keith-wood.name/countdown.html
Tab Timezones has the PHP code you'll need to add to serverTime.php for your script to use that. Also may want to fully qualify that to something like url: 'http:yourdomain.com/serverTime.php' But using that it should use your server time not your local PC time. If your server is on your local PC, then well... it would change.
I went to their site, with their example, and changing my system time affects their countdown as well. Their code relies on local system times.
What I see when you get the server time form the ajax call, it is not creating the JavaScript date object.
I searched and below worked for me.
// Split timestamp into [ Y, M, D, h, m, s ]
var t = "2010-06-09 13:12:01".split(/[- :]/);
// Apply each element to the Date function
var d = new Date(t[0], t[1]-1, t[2], t[3], t[4], t[5]);
alert(d);
// -> Wed Jun 09 2010 13:12:01 GMT+0100 (GMT Daylight Time)

Categories