I have problem in comparing two dates. User will choose date from Datepicker with format ('Y-m-d'). If input is not equal to the current date then error message will showed up else output will be displayed.
I have this code:
$today = date("Y-m-d");
$date = $_REQUEST['selected_date']; // date selected
$first = strtotime($today);
$second = strtotime($date);
if ($first != $second){
//error message
}else{
//some code
}
This works fine in local but when i try to upload it, its not working anymore. Instead, the previous date can be accepted not the current date.
Probably the timezone is set differently on the server than from your local machine.
Try printing out the values of $first and $second.
You can (and should) set the timezone used by PHP with date_default_timezone_set() if you're using any of the old-style PHP date functions (date, strtotime etc).
Though I recommend using the DateTime & DateTimeZone classes with new code, they're nicer to work with, especially if you're doing anything involving multiple timezones.
Is there any possibility that the server is in a different time zone than where the request is coming from? I'd think this could lead to a mismatch.
Hopefully I understand your situation correctly. Attacking this directly will fail a lot of times because the server time zone (which you get through date()) will be different from the client time zone. To avoid this problem you need to send the client time to your server via javascript. jQuery example may look like this:
var date = new Date();
$.post("index.php", { today: (today.getMonth() + 1) + "/" + today.getDate() + "/" + today.getFullYear()}, function(data) {
alert(data); //server response here
});
on the server you get your client's today date as a string via $_POST['today']. Then you can decide what to do with it and output it to your client.
Alternatively, the problem you are describing can be solved just by JavaScript without sending it to your server unless you want to do something with it on your server
Related
I have tried many times to store the exact date which I have selected. But when saving, it will take the previous date. I have tested in many ways, the angular file will pass the same selected date. When the sql query is executed, then it will take the incorrect date. can anyone please help me to solve this?
Below is my code.
html code:
<td class="data_field">
<input class="form-control" type="date" name="date_main_domain" ng-model="domain.date_main_domain" id="date_main_domain" required value="{{domain.date_main_domain}}">
</td>
sql query:
$database->execute( "UPDATE domain_information SET date_main_domain='$dateMainDomain' WHERE id=$domainId" );
You need a valid date for the database to accept it, format your date object
function formatDate(date) {
var d = new Date(date),
month = '' + (d.getMonth() + 1),
day = '' + d.getDate(),
year = d.getFullYear();
if (month.length < 2) month = '0' + month;
if (day.length < 2) day = '0' + day;
return [year, month, day].join('-');
}
// date object to save
var date = new Date(formatDate($scope.domain.date_main_domain));
Sounds like a timezone issue to me.
I guess on angular side the local timezone of the browser is taken.
Then you send it to the server. From my experience i would say it's beeing transfered as a utc time which represents the same time as the local time in the browser. So, for instance if the user is located in china at 12:00 (UTC+8), i guess 04:00 UTC-0 will be transfered.
At the server side the date will be set. Dependent on the methods you call on the date object you will see the utc-0 or the server timezone based representation.
You should analysis the date inside your request which goes to the server. If you just want the right day and don't care about the local timezone of the user you might concider to change the timezone of your date to Utc-0 on frontend side before you send it. (use a copy, so that you don't affect ypur model date)
I've been struggling to get an exact answer for this question. There are many that are close to what I'm wanting but seem to still be just off. The application of this is to ensure that a booking can't be made for a past date.
I have a form which has an input for time & another for date. Firstly, I wan't to take both of these inputs & convert them to a timestamp.
This code returns nothing
$time_date = sprintf("%s %s", $pDate, $pTime);
$objDate = DateTime::createFromFormat('H:ia d/m/Y', $time_date);
$stamp = $objDate->getTimestamp();
echo $stamp;
So I've have tried using something like this
$pDate = $_POST['pDate'];
$pTime = $_POST['pTime'];
$full_date = $pDate . ' ' . $pTime;
$timestamp = strtotime($full_date);
echo $timestamp;
But for some reason it is returning an incorrect timestamp. (i've been using an online converter) 02/06/2014 as date & 12:23am as time, is not 1401625380. This according to the converter is Sun, 01 Jun 2014 12:23:00 GMT.
Does someone have working code for returning a timestamp of both time & date inputs?
Secondly I want to compare this timestamp with a specified one & check to see if it is greater than. I've created a timestamp for my timezone with this
$date = new DateTime(null, new DateTimeZone('Pacific/Auckland'));
$cDate = $date->getTimestamp();
echo $cDate;
and will simply have an if statement which compares the two and echos the appropriate message.
I feel as though there are multiple question on here that are ALMOST what I'm wanting to achieve but I can't manage to get them working. Apologies for the near duplicate.
Note: I'm using ajax to post form data (if this could possibly interfere).
Your second code snipped is correct. Assuming it's in datetime format (Y-m-d H:i:s).
From php manual about strtotime():
Each parameter of this function uses the default time zone unless a time zone is specified in that parameter.
Check your PHP default time zone with date_default_timezone_get() function.
To compare two dates, be sure they both are in same time zones.
For datetime inputs I personally use jQuery UI timepicker addon.
you receiving the time and date in string format - so i don't believe the ajax can interfere.
as for your question:
first of all - find out what is the locale timezone of your server. you can do it by this function: date_default_timezone_get.
if the answer doesn't suit you - you can use its "sister": date_default_timezone_set, and change it to whatever value you need (like 'Pacific/Auckland' - see the documentation there). it is also recommended to return it to the original value after you finish your stuff.
i believe fixing your locale timezone will solve your issue.
I want to display two dates/times on my page
the server one, taken from the MySQL Server
the client one, taken from JavaScript
Since the output wasn't right, I started digging through my code and found something weird: I formatted the same timestamp in both php and javascript (see the code below) and the results differed by 3 hours.
timestamp: 1369855189
PHP:
var_dump( date( 'H:i:s', $timestamp ) );
Output: "19:19:49"
JavaScript:
dts = new Date( timestamp * 1000 );
var hours_s = dts.getHours();
var minutes_s = dts.getMinutes();
var seconds_s = dts.getSeconds();
current_server_time = hours_s + ":" + minutes_s + ":" + seconds_s";
Output: "22:19:49"
Does anyone know why this is happening? Does anyone know a workaround?
You and your server are probably not on the same timezome.
Try with javascript:
var hours_s = dts.getUTCHours();
var minutes_s = dts.getUTCMinutes();
var seconds_s = dts.getUTCSeconds();
The timestamp will be UTC...but once you put it into a PHP date object, it will have the timezone of the server. Once you put it into JavaScript, it will have the computer's local timezone. To set the timezone of the server in PHP, you can use this (replacing the timezone with yours) and see if that fixes it for you:
date_default_timezone_set('America/Chicago')
Obviously, to change the timezone for JavaScript requires changing your computer's timezone.
Is the php being executed in a server different from the machine where the JavaScript is parsed?
Either way, there is a workaround if you can work with gmt time:
Use the gmdate in your PHP script.
Use dts.getUTCHours() (and similar functions for the rest, prefixing UTC) in your JS. Check the ECMAScript standard p. 174. for more details.
If you want to work with local time, review the locale configuration of both server and client machines.
My problem is as follows:
I want to display nepalese standard time in my website,so i set default timezone of my
website to 'Asia/kathmandu' using command: php_value date.timezone 'Asia/kathmandu' in htaccess file.
when i display time using any php functions like strftime() or date() ,it shows the nepalese standard time,
But when i use javascript function new Date(<?php echo time()*1000; ?>),it displays
the time of my personal pc i am using to view my website.
How can i display correct time using javascript date functions? Can anybody help me out?
Your issue is because javascript (actually ECMAScript) date objects are based on a UTC time value. When you do:
new Date(<?php echo time()*1000; ?>)
you are passing a UTC millisecond time value to the Date constructor, which then creates a date object. When you use the usual Date methods to format a string, or use Date.prototpye.toString or Date.prototype.toLocaleString, you will get a string based on the client's locale. Note that all these strings are implementation dependent and vary widely for the locale version.
If you want the timezone of the server, then use the server to set it. Or you can send a time zone offset in minutes to be applied to the local time to get back to Nepalese Standard Time (UTC + 5:45). Note that in ECMAScript, the time zone offset is minutes to be added to the local time to get UTC, whereas it is more normal to define the offset in minutes to be added to UTC to get the local time.
So to get NST:
function toNST(timeValue) {
function z(n) {return (n<10? '0' : '') + n}
var d = new Date();
var nstOffset = 5 * 60 + 45;
d.setMinutes(d.getMinutes() + d.getTimezoneOffset() + nstOffset);
return z(d.getHours()) + ':' + z(d.getMinutes()) + ':' + z(d.getSeconds());
}
alert(toNST(+(new Date()))); // about 11:07:17 at the moment
Use
new Date(Date.NPT(year, month, day, hour, minute, second))
Call the time via ajax from your server. That has the advantage of a better code maintanance. If you change the time again (e.g. if you want to use the code for another location) you have only to change the time in .haccess.
The server my PHP script is running on is set to UTC. I can't seem to figure out a way to set all dates to the browser's timezone. All dates displayed are formatted using PHP's date() function.
I know that via JavaScript's getTimezoneOffset() function, I can get the browser's current UTC offset (-4, in my case). How can I tell PHP to use this offset? I can use date_default_timezone_set(), but how do I convert an offset, say -4, to a time zone string, say America/New_York?
Note: The server is running PHP 5.1.6 (with no DateTime class) and I am using CodeIgniter.
As per the comment above- you could use a cookie...:
Javascript:
var today = new Date();
function SetCookie(cookieName,cookieValue,nDays) {
var expire = new Date();
if (nDays==null || nDays==0) nDays=1;
expire.setTime(today.getTime() + 3600000*24*nDays);
document.cookie = cookieName+"="+escape(cookieValue)
+ ";expires="+expire.toGMTString();
}
SetCookie("datecookie", today, 30);
window.location.href=window.location.href
PHP:
echo date("m d Y", strtotime($_COOKIE['datecookie']));
Because Javascript is client based and PHP is server based, they will not communicate. To tell the server the browser time, you will need to send information from the client, perhaps via Ajax, posting the browser time. The target PHP script should then handle/output this as appropriate. One other (obtuse) option is to attempt to geolocate the user based on IP, then guesstimate the correct time for that location- however this is inefficient for this purpose.
"I know I can use date_default_timezone_set(), but how do I convert an offset, say -4, to a time zone string, say America/New_York?"
Simply look at the comments associated with the documentation for that function. Comment #99006 does the work for you. You just need to get the timezone offset from the user.