Does PHP provide a way to set the system date within a script?
i.e. so that I can make date('Y') return 1999 even though it's currently 2021.
I want to be able to quickly set the system date for debugging/testing purposes.
Perhaps "system date" is the wrong phrase. I only want it to be changed for the same script, whilst it's running.
Manipulating the server date for a test creates a host of other problems. Don't do it!
You can always use a timestamp as a second parameter in your script. With strtotime() you can test the script with any date.
$ts = time();
$ts = strtotime('1999-01-01');
echo date('Y', $ts); //1999
After the test, the line is commented out with strtotime and the time stamp is then initialized with time(). The date ('Y') then behaves like without a second parameter.
$ts = time();
//$ts = strtotime('1999-01-01');
echo date('Y', $ts); //2021
I don't think there is a way using strictly PHP, however according to This answer, you can use shell_exec("date 09-09-99") to run a shell command and set the time of the system like that.
I wouldn't recommend it though, since it could mess with something else.
Related
I am trying to get the local time using php. I wrote two different versions, but they both give the wrong time
date_default_timezone_set('UTC');
$now = new DateTime();
echo $now->getTimestamp();
Another way
date_default_timezone_set('America/New York');
echo strtotime("now")."<br/>";;
$now = new DateTime();
echo $now->getTimestamp();
In both cases I get the time 4 fours ahead of my local time. There is any other way to get the local time?
DateTime::getTimestamp() returns unix timestamp. That number is always UTC. What you want is format the date according to your time zone.
$dt = new DateTime("now", new DateTimeZone('America/New_York'));
echo $dt->format('m/d/Y, H:i:s');
Or use a different date format, according to what you need.
Also, you can use DateTime library for all your date needs. No need to change server's default timezone every time you want to fetch the date.
Simply use function date_default_timezone_set(). Here is example:
<?php
date_default_timezone_set("Asia/Dhaka");
echo date('d-m-Y h:i:s A');
?>
Hope it will help,
Thanks.
You need to use javascript because you want the value of time from the client. PHP is a server-side language that evaluates on the server and sends results to the client. So if you try to pull a date/time using a PHP function, it's going to pull the date from the server, which is not always in the client's timezone.
You can do this in a javascript function and then reference the value in the display.
var thisDateTime = new Date();
If you don't want to use timezone you can use this mix of windows and php commands:
<?php
$D = exec('date /T');
$T = exec('time /T');
$DT = strtotime(str_replace("/","-",$D." ".$T));
echo(date("Y-m-d H:i:s",$DT));
?>
I'm wondering why nobody has mentioned localtime(time()); in PHP with indexed key array result or localtime(time(), true); with associative key array result.
For the record, I found the only solution to read the real hour of the machine is to read the information outside of PHP (javascript, shell or other processes). Why?
For example, let's say we have an hour based in daily-saving. What if the timezone of the OS (Windows in my case) is not in sync with the timezone of PHP, I mean, it could be calculated differently. Or maybe the machine is using a different hour and it is ignoring the daily-saving hour.
Right now, my zone is UTC -4 Santiago 9:35 pm (with daily saving). However, PHP considers as 10:35 PM (using localtime,time,date and DateTime).
If anyone here wanted to get the local time according to the user's timezone (dynamically), then you can consider the following code:
$ip = $_SERVER['REMOTE_ADDR'];
$ipInfo = file_get_contents('http://ip-api.com/json/' . $ip);
$ipInfo = json_decode($ipInfo);
$timezone = $ipInfo->timezone ?? "UTC";
$dt = new DateTime("now", new DateTimeZone($timezone));
echo $dt->format('Y-m-d H:i:s');
The above code will get the user's local timezone and print the time according to that.
If you wanted to test the above code on your localhost then make sure to hard code your IP address there because the API can't provide you the timezone based on your local address (127.0.0.1), but the above code works fine on the
live server.
For Localhost, do:
$ip = '-------'; //your IP address
You can solve this problem by using localtime() function or through date_default_timezone_set() function.
Learn more about the localtime() function reffer:
http://php.net/manual/en/function.localtime.php
or
Learn more about the date_default_timezone_set() function reffer http://www.php.net/manual/en/function.date-default-timezone-set.php
i think this must help you..
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 have tried using php date function() like as follows
$date=date('Y-m-d').' '.date('H:i:s');
echo $date;
the output displayed is 2013-04-03 09:04:02.. but my system is 02:49 pm...
What time is being displayed for me? I tried changing the internet timing even then I am getting the same answer ?
First off, it is not necessary to use the date function twice. This will do the same thing:
echo date('Y-m-d H:i:s');
Second, you need to set PHP's date.timezone. This can be done in the php.ini file, but it can also be done using the date_default_timezone_set function, like this:
date_default_timezone_set('Europe/Amsterdam');
The string that you have to put in can be found in the documentation.
It may also be worth noting that you can tell the date function to use any time. This is done by passing in a *nix timestamp as the second argument. For example:
// One week ago from now
echo date('Y-m-d H:i:s', time()-604800);
It will show server's time only. If possible compare with your server time. If you want to use local machine's time you need to go with JAVASCRIPT.
And another suggestion,
You don't have to use individually to display date & time. You can achieve this in a single statement like this.
$date=date('Y-m-d H:i:s');
You will get the same format 2013-04-03 09:04:02
check for your system timezone and your default timezone in php by opening phpinfo()
I've some problem with make a simple PHP function to work on my webspace meanwhile it works like expected at my localhost server.
The problem is the following calculation:
echo $Formated = date("Ymd",strtotime("last day of next month"));
This script dosen't seem to work b/c i simply gets the default date 19691231 instead of the correct one 20110630 when running it on my server.
I use windows (XAMP) as my localhost server so i guess there must be some form of problem that lies within the two platforms way of handling it?
strtotime is notoriously problematic going cross-version, so I'd recommend a vast simplification. You can use the 't' character in the date format to represent the last day of the month, then reduce your strtotime call to simply return some timestamp for the next month.
echo $Formated = date("Ymt", strtotime("next month"));
dont use of if month name is not given
try with
date('m/d/y', strtotime('last day next month'));
OR
date('m/d/y', strtotime('last day of march')); // give the month name with of
Reference
Forget Migration and Deployment, in fact strtime is not reliable. Navigate PHP's official site: Check the strtotime manual, especially this comment.
If you have a MySQL connection available, SELECT DATE_ADD( '2011-05-31', INTERVAL 1 MONTH ) would be less redundant since the (correct) functionality is already implemented without you having to implement it yourself.
I was using this query to fill my values:
mysql_query("INSERT INTO 'drivers'(coupon,loyalty,etairia,package,pump,date,merchant,public,private,
amount,plate,nonce)VALUES('".$_REQUEST['coupon']."','".$_REQUEST['loyalty']
."','".$_REQUEST['etairia']."','".$_REQUEST['package']."',0,NOW(),'".$_REQUEST['m']."
','".$_REQUEST['pu']."','".$_REQUEST['pr']."','".$_REQUEST['amount']."',
'".$_REQUEST['plate']."','".$_REQUEST['nonce']."');");
This is working fine, but with NOW() I have the server hour so I want to convert it to my local hour.
I found this on another question:
$date = new DateTime();
$date->setTimezone(new DateTimeZone('Europe/Athens'));
$fdate = $date->format('Y-m-d H:i:s');
I printed it and it returned the correct hour.
Finally I tried to put it inside the query instead of NOW() but when I run it it doesn't even make a row to my base.
This is my code now:
mysql_query("INSERT INTO `drivers`.`pay`(coupon,loyalty,etairia,package,pump,date,merchant,public,
private,amount,plate,nonce)VALUES('".$_REQUEST['coupon']."','"
.$_REQUEST['loyalty']."','".$_REQUEST['etairia']."','".$_REQUEST['package']
."',0,'".$fdate."','".$_REQUEST['m']."','".$_REQUEST['pu']."',
'".$_REQUEST['pr']."','".$_REQUEST['amount']."','".$_REQUEST['plate']."','"
.$_REQUEST['nonce']."');");
My php version is 5.5.9
To get local time:
echo date("Y-m-d H:i:s");
To get global time:
echo gmdate("Y-m-d H:i:s");
Or set your timezone something like this:
date_default_timezone_set('Europe/Athens');
print date('Y-m-d H:i:s')."\n";
I will suggest you, do not use mysql_.It is deprecated from the latest version of PHP.Use mysqli_ instead of this.
As has already been suggested, try using "date_default_timezone_set" and "date" to get the date in your local timezone.
I would also recommend a couple of other things:
Use mysqli instead of mysql functions as mysql functions are deprecated
Escape your strings! To avoid SQL injection use mysqli_real_escape_string on anything that comes from the request
I understand that your question is "what is wrong with this mysql query ?". The problem is that you don't see which error is produced by MySQL.
This case is known for PHP as a "WSOD" or White screen of death : nothing is displayed, generally because of some error setting (php function error_reporting).
If you take a look at this page, you will find a way to declare a error handler, which is a great time saver when programming PHP. You will also read the reason of your error and you then can explain it to us all. :-)
Check out UNiX_TIME stamp. It will store as a big int . It's basically seconds count from a particular date which the clock was set . It's a good way as it gives you flexibility in retrieving in any format you want. You can convert it in client side. Hope this helps
You can use date('Y-m-d H:i:s') or gmdate('Y-m-d H:i:s') to get the current date and time. You will need to make sure that your date column is set as a DATETIME type
I don't know if you still need it, but with the following code
$timezone = +1;
$date = gmdate("Y-m-j H:i:s", time() + 3600*($timezone+date("I")));
You can change the timezone as you want (for example my timezone is GMT + 1 where I am now) and with the date you also no need to worry about when daylight time changes.
For you is
$timezone = +2;