How can I set the internal time of the PHP interpreter? - php

I have written a function in PHP which will print the third Monday of every month.
I now want to test the function if the function will work next month, without having to wait till next month.
My idea is that I could test how the function would work in the future by internally setting PHP's time to next month and running the function.
I was hoping there would be a Date Time ini setting which I could insert before my function to shift the time into the future, something like
<?php
$one_month_from_now = time() + 2592000;
ini_set('php_internal_time', $one_month_from_now);
function print_third_monday() {
// ....
}
print_third_monday();
Is is possible to change PHP's internal time like this? if so, how?

echo date("y-m-d H:i:s D");//17-03-16 10:43:38 Thu
echo PHP_EOL;
echo date("y-m-d H:i:s D",strtotime("+1 month"));//17-04-16 10:43:38 Sun

How about a better function that does the same functionality & you can cross check with ease:
<?php
echo getThirdTuesdayofMonth(3,2017);
function getThirdTuesdayofMonth($month, $year) {
$thirdTuesday='';
$no_of_days = cal_days_in_month(CAL_GREGORIAN, $month, $year);
$tue_iter=0;
for($i=1;$i<=$no_of_days;$i++) {
if(date('l',strtotime($i.'-'.$month.'-'.$year))=='Tuesday') {
if($tue_iter==3) {
$thirdTuesday = date('dS F Y', strtotime($i.'-'.$month.'-'.$year));
}
$tue_iter++;
}
}
return $thirdTuesday;
}

Related

PHP Wrong time after setting timezone

I stumbled onto a really weird problem:
For my task I wrote a method that would give me the current date in a specific format,
another method would then extract the date so I could compare it with dates in the database.
public static function getCurrentDate()
{
return date("Y-m-d H:i:s a");
}
public static function extractDate($date)
{
return date("Y-m-d", strtotime($date));
}
Because I've noticed that the time wasn't right, I've set the default timezone at the beginning of the script like this:
date_default_timezone_set('Europe/Berlin');
Running this script, I've noticed that it gives the wrong output, maybe you could already help me here.
$currentDate = getCurrentDate();
echo $currentDate."\n";
$extractedDate = extractDate($currentDate );
echo $extractedDate."\n";
Output:
2020-08-25 21:58:13 pm
1970-01-01
Then I tried it in another way with DateTime, where it still produced the wrong output
public static function extractDate($date)
{
$timezone = new DateTimeZone('Europe/Berlin');
$dt = DateTime::createFromFormat("Y-m-d H:i:s a", $date, $timezone);
return $dt->format("Y-m-d");
}
Output:
2020-08-25 21:58:13 pm
2020-08-26
I would understand if there was an error so it would lead to the Unix epoch again, but this time it somehow added a day.
It would be nice if you knew where my error at the first approach was and I'm also really interested to hear why PHP behaves like that in the second approach
Change:
public static function getCurrentDate()
{
return date("Y-m-d H:i:s a");
}
to
public static function getCurrentDate()
{
return date("Y-m-d H:i:s");
}
and you are all set.
In 24h time you do not need the a or am/pm, which makes the datetime unrecognizable via strtotime, it cannot convert it , and it returns false, thus the invalid date 1970-01-01which is qeuivalent tounixtime = 0`

PHP - date scheduling

hello is there way to locked a page based on the input date. Like for example admins input june 18 , 2018 starttime to june 22, 2018 endtime . some users function is blocked or disabled until the starttime and be disabled again on the endtime. unfortunately i can't post a code because i dont know how to do it. any help is very much appreciated
Hello once solution is you need to change it in php.ini and disabled_function but that make not sense for user defined function and also can't change at run-time so i would like to prefer you alternate solution is
<?php
$startTime = strtotime('2008-09-22');
$endTime = strtotime('2008-09-25');
$now = new DateTime();
$currentDate = $now->format('Y-m-d');
$currentTime = $now->getTimestamp();
function a(){
if($currentTime>$startTime && $currentTime<$endTime){
// in this scope this is enable so you can put logic here
} else {
// in this scope this is disable section so you can return error warning and false
return false;
}
}
?>

PHP, Date: A Dot appended to a month short representation

I have
date("M.", $datetime)
I want to get this output:
Jan.
Feb.
Mar.
Apr.
May (no dot necessary)
Jun.
Jul.
…
I dont like the idea of an if-statement to check the length/number of month every time a date is generated.
Is there a approach that is more simple? Like changing the month-name in general? Or hooking into the date function itself to implement an if-statement that runs every time the date function runs.
Thanks
If you don't want the dot to appear after May month, you will need a check of some sort - which normally is an if. You could do something like this, check if the month returned by date() isn't May, and add a dot after if it isn't.
$date = date("M", $datetime);
if (date("M") != "May")
$date .= ".";
Otherwise you'd need to implement a function of your own, but in the end - you will have to end up with this again, there's really no way around it - and this is by far the simplest and cleanest way.
You could wrap this into a function. You can't alter the date() function directly, but you can create one of your own.
function my_date($format, int $timestamp = null) {
if ($timestamp === null)
$timestamp = time();
$date = date($format, $timestamp);
if ($format == "M" && date("M", $timestamp) != "May")
$date .= ".";
return $date;
}
Then use it as
echo my_date("M", $datetime);
This seems to be a bit of a hammer to crack a nut, or to avoid an IF statement in this case, but you can create an array with your month names in it and use that to output different month names if you like
$m_arr = [0,'Jan.','Feb.','Mar.','Apr.','May','Jun.',
'Jul.', 'Aug.', 'Sep.','Oct.','Nov.','Dec.'];
$m = (int)date('n', $datetime);
echo $m_arr[$m];

PHP Checking if outputted date is less than current date

I have the following function which works well but would like to check the returned date and compare with the current date if before current date to show something if current or in future show as normal.
Function:
function dateFormat( $old, $correction ) {
$old_date_timestamp = strtotime( $old );
$new_date = date( 'jS F Y', $old_date_timestamp + $correction );
return $new_date;
}
Call:
echo '<li class="list-group-item">Support Expires: ' . dateFormat($purchase_data['verify-purchase']['supported_until'], 11*60*60 . '</li>');
Output:
2nd March 2016
So as not today's date and/or before today's date would like to echo a message, else just show the date.
In PHP it is very simple to compare two different dates using < = > like you normally compare numbers. The only step prior to this is below:
//Tell PHP that the value in variable is a date value
$date_1 = date_create("2017-05-29"); //This value can be any valid date format
date_1_formatted = date_format($date_1, "Y-m-d"); //This formats the date_1
//Now you can simply put the second date, for example, today.
$date_2 = date_create("2017-04-29"); //This value can be any valid date format
date_2_formatted = date_format($date_2, "Y-m-d"); //This formats the date_1
//For current date, it is simpler
$date_today_formatted = date("Y-m-d");
//Now you can compare these two dates easily
if ($date_1 < $date_today_formatted) {
echo "Date 1 falls before today.";
}
else {
echo "Date 1 falls after today.";
}
Hope this helps!
I managed to work it out using the following 2 functions:
function dateFormat( $old, $correction ) {
$old_date_timestamp = strtotime( $old );
$new_date = date( 'jS F Y', $old_date_timestamp + $correction );
return $new_date;
}
function checkLicenceSupport($licence_date) {
$date_now = new dateTime();
$date_set = dateFormat($licence_date, 11*60*60);
if ($date_now > $date_set) {
return 'date expired';
} else {
return 'date valied';
}
}
I have the following function which works well, but would like to
check the returned date and compare with the current date.
If it is before the current date, show something.
If it is the current date, or in future, show as normal.
I needed to rewrite your question, because lack of grammar and punctuation made it confusing. No offense intended.
Your call code has the closing parenthesis for your function call is placed wrongly.
dateFormat($purchase_data['verify-purchase']['supported_until'], 11*60*60)
It is more readable to use full days or hours (in seconds):
11*86400 //(11 Days);
11*3600 //(11 Hours);
The function and code, as you have it now, will always return a date in the future of the date you've submitted via the call. (I can't tell from your question whether this was intended or not).
Currently, there is no "comparison" in your function. But your question indicates you want to compare the submitted date to the current date and then do something in certain cases.
If you are going to use a Unix timestamp, then there's no need for multiple formatting, compare the two dates in Unix, then format the result.
function dateCompare($submittedDate){
//This is only needed if your submitted date is not a unix timestamp already
$submittedDate = strtotime($submittedDate);
$currentDate = time(); // Creates timestamp of current datetime
if($submittedDate < $currentDate) {
//show something i.e. return "Support Has Expired";
}else {
return date('jS F Y', $submittedDate);
}
}
echo '<li class="list-group-item">Support Expires: '.dateCompare($purchase_data['verify-purchase']['supported_until']).'</li>';

PHP strtotime timezone issue with '0:00 GMT'

So I have a function get_start_of_day($time), which I want to give me a timestamp representing the very very first minute of the day in which $time, a timestamp, falls.
Originally, I was using:
function get_start_of_day($time) {
return strtotime('0:00 GMT', $time);
}
which seemed to be working just fine.
Then I realized that for certain times it was returning midnight of the previous day, for example:
$x = 1432468800;
echo gmdate('Y-M-d H:i:s', $x);
$y = get_start_of_day($x);
echo gmdate('Y-M-d H:i:s', $y);
outputs:
2015-May-24 12:00:00
2015-May-24 00:00:00
BUT:
$x = 1432432800;
echo gmdate('Y-M-d H:i:s', $x);
$y = get_start_of_day($x);
echo gmdate('Y-M-d H:i:s', $y);
outputs:
2015-May-24 02:00:00
2015-May-23 00:00:00
So at some value for $x, the output was wrongly jumping to the day previous and outputting that. Some further experimentation revealed that the value for $x at which the jump happens is 4am, i.e. the timestamp 1432440000 gave the proper result, but the timestamp 1432439999 did not.
Now, according to Epoch Converter I'm in GMT-4:00. It seems as though this must somehow be the cause. I've updated the function to:
function get_start_of_day($time) {
$start_of_day = strtotime('tomorrow 0:00 GMT', $time);
if ($start_of_day > $time) {
$start_of_day -= 86400;
}
return $start_of_day;
}
which seems to work fine, but I can't help but wonder...what's going on here? Does anybody know?
Thanks in advance! :)
EDIT: I'm using GMT in case I move to a new server...I would hate to be getting different start-of-day values after I hypothetically move, which may not sync up with the old values. So I figured, just use GMT for everything, all the time.
Use strtotime('today', $time). You will need to use date_default_timezone_set or date.timezone INI setting to select your time zone.

Categories