PHP date incrementing error - php

I am trying to create a calendar where the date increments and each date is clickable, which links to a search. The strange part is that the date stops at 25th October, and stops incrementing. i.e 24th, 25th, 25th, 25th...
Its doesn't matter which day the calendar started with (been staring at it for a few days), but at 25th it stops incrementing.
Grateful for any advice.(The 2nd part after the gap is probably irrelevant, but including it in case there could be any link)
for ($i = 1; $i <= 30; $i++){
$date = date("d-m-Y", strtotime($date) + 86400);
array_push($array_date, $date);
$separatedate = explode('-', $date);
$getday = date("l", strtotime($date));
print "<button class='submitsearch btn' value=$array_date[$i]>" . ltrim($separatedate[0], '0') . "<br>" . $getday . "<br></button>";
if (!checkdate($separatedate[1] , $separatedate[0]+1 , $separatedate[2])) {
$nextmonth = date("F", strtotime($date) + 86400);
print "<strong>". $nextmonth . "</strong><hr/>";
}
}

This is the problem:
$date = date("d-m-Y", strtotime($date) + 86400);
You appear to be relying on that to increment the date. Usually, that will be fine... but it isn't when we have a 25 hour day, due to daylight saving time changes.
I suggest you use date/time arithmetic functions (e.g. date_add) designed to add a day, rather than adding 24 hours. Or make sure all arithmetic is done in UTC, which won't have any time zone changes. In general, I would try to avoid performing any more string conversions than you really need to: keep a variable representing the date/time in an idiomatic way, and perform arithmetic on that - then just format that variable when you need to. I don't see any need to call strtotime anywhere, if you do this right.

Related

Generating a date based on a weekinterval, a day, and an existing date

I have a database with different workdates, and I have to make a calculation that generates more dates based on a weekinterval (stored in the database) and the (in the database stored) days on which the workdays occur.
What my code does now is the following:
Read the first two workdates -> Calculate the weeks inbetween and save the week interval
Read all the workdates -> fill in the days on which a workdate occurs and save it in a contract.
Generate workdates for the next year, based on the week interval.
The point is: for each week with a week interval of 1, more days of the week should be saved as a workdate. I've used this code to do this, but it doesn't work.
// Get the last workdate's actdate.
$workdate_date = $linked_workdate['Workdate']['workdate_actdate'];
// Calculate the new workdate's date
$date = date("Y-m-d", strtotime($workdate_date . "+" . $interval . " week"));
// If 'Monday' is filled in for this contract, calculate on which day the
// Monday after the last interval is. Same for each day, obviously.
// The days are boolean.
if ($contract['Contract']['contract_maandag'] = 1){
$date = date("Y-m-d", strtotime($date, "next Monday"));
}
if ($contract['Contract']['contract_dinsdag'] = 1){
$date = date("Y-m-d", strtotime($date, "next Tuesday"));
}
// After this, save $date in the database, but that works.
Here is the error that i get:
strtotime() expects parameter 2 to be long, string given
I'm quite stuck right now, so help is appreciated!
if ($contract['Contract']['contract_maandag'] = 1){
if ($contract['Contract']['contract_dinsdag'] = 1){
This won't work. You're doing an assignment (=), so it's always true. But you want a comparison (===). It is recommended to do always (except required otherwise) to use strict (===) comparison.
Well, the = doesn't seem to be the problem, since the error is about the part that's after the comparison. Try
strtotime("$date next Monday");

PHP Adding 15 minutes to Time value

I have a form that receives a time value:
$selectedTime = $_REQUEST['time'];
The time is in this format - 9:15:00 - which is 9:15am. I then need to add 15 minutes to this and store that in a separate variable but I'm stumped.
I'm trying to use strtotime without success, e.g.:
$endTime = strtotime("+15 minutes",strtotime($selectedTime)));
but that won't parse.
Your code doesn't work (parse) because you have an extra ) at the end that causes a Parse Error. Count, you have 2 ( and 3 ). It would work fine if you fix that, but strtotime() returns a timestamp, so to get a human readable time use date().
$selectedTime = "9:15:00";
$endTime = strtotime("+15 minutes", strtotime($selectedTime));
echo date('h:i:s', $endTime);
Get an editor that will syntax highlight and show unmatched parentheses, braces, etc.
To just do straight time without any TZ or DST and add 15 minutes (read zerkms comment):
$endTime = strtotime($selectedTime) + 900; //900 = 15 min X 60 sec
Still, the ) is the main issue here.
Though you can do this through PHP's time functions, let me introduce you to PHP's DateTime class, which along with it's related classes, really should be in any PHP developer's toolkit.
// note this will set to today's current date since you are not specifying it in your passed parameter. This probably doesn't matter if you are just going to add time to it.
$datetime = DateTime::createFromFormat('g:i:s', $selectedTime);
$datetime->modify('+15 minutes');
echo $datetime->format('g:i:s');
Note that if what you are looking to do is basically provide a 12 or 24 hours clock functionality to which you can add/subtract time and don't actually care about the date, so you want to eliminate possible problems around daylights saving times changes an such I would recommend one of the following formats:
!g:i:s 12-hour format without leading zeroes on hour
!G:i:s 12-hour format with leading zeroes
Note the ! item in format. This would set date component to first day in Linux epoch (1-1-1970)
strtotime returns the current timestamp and date is to format timestamp
$date=strtotime(date("h:i:sa"))+900;//15*60=900 seconds
$date=date("h:i:sa",$date);
This will add 15 mins to the current time
To expand on previous answers, a function to do this could work like this (changing the time and interval formats however you like them according to this for function.date, and this for DateInterval):
(I've also written an alternate form of the below function here.)
// Return adjusted time.
function addMinutesToTime( $time, $plusMinutes ) {
$time = DateTime::createFromFormat( 'g:i:s', $time );
$time->add( new DateInterval( 'PT' . ( (integer) $plusMinutes ) . 'M' ) );
$newTime = $time->format( 'g:i:s' );
return $newTime;
}
$adjustedTime = addMinutesToTime( '9:15:00', 15 );
echo '<h1>Adjusted Time: ' . $adjustedTime . '</h1>' . PHP_EOL . PHP_EOL;
get After 20min time and date
function add_time($time,$plusMinutes){
$endTime = strtotime("+{$plusMinutes} minutes", strtotime($time));
return date('h:i:s', $endTime);
}
20 min ago Date and time
date_default_timezone_set("Asia/Kolkata");
echo add_time(date("Y-m-d h:i:sa"),20);
In one line
$date = date('h:i:s',strtotime("+10 minutes"));
You can use below code also.It quite simple.
$selectedTime = "9:15:00";
echo date('h:i:s',strtotime($selectedTime . ' +15 minutes'));
Current date and time
$current_date_time = date('Y-m-d H:i:s');
15 min ago Date and time
$newTime = date("Y-m-d H:i:s",strtotime("+15 minutes", strtotime($current_date)));
Quite easy
$timestring = '09:15:00';
echo date('h:i:s', strtotime($timestring) + (15 * 60));

PHP DateTime credit card expiration

I'm trying to use DateTime to check if a credit card expiry date has expired but I'm a bit lost.
I only want to compare the mm/yy date.
Here is my code so far
$expmonth = $_POST['expMonth']; //e.g 08
$expyear = $_POST['expYear']; //e.g 15
$rawExpiry = $expmonth . $expyear;
$expiryDateTime = \DateTime::createFromFormat('my', $rawExpiry);
$expiryDate = $expiryDateTime->format('m y');
$currentDateTime = new \DateTime();
$currentDate = $currentDateTime->format('m y');
if ($expiryDate < $currentDate) {
echo 'Expired';
} else {
echo 'Valid';
}
I feel i'm almost there but the if statement is producing incorrect results. Any help would be appreciated.
It's simpler than you think. The format of the datess you are working with is not important as PHP does the comparison internally.
$expires = \DateTime::createFromFormat('my', $_POST['expMonth'].$_POST['expYear']);
$now = new \DateTime();
if ($expires < $now) {
// expired
}
You can use the DateTime class to generate a DateTime object matching the format of your given date string using the DateTime::createFromFormat() constructor.
The format ('my') would match any date string with the string pattern 'mmyy', e.g. '0620'. Or for dates with 4 digit years use the format 'mY' which will match dates with the following string pattern 'mmyyyy', e.g. '062020'. It's also sensible to specify the timezone using the DateTimeZone class.
$expiryMonth = 06;
$expiryYear = 20;
$timezone = new DateTimeZone('Europe/London');
$expiryTime = \DateTime::createFromFormat('my', $expiryMonth.$expiryYear, $timezone);
See the DateTime::createFromFormat page for more formats.
However - for credit/debit card expiry dates you will also need to take into account the full expiry DATE and TIME - not just the month and year.
DateTime::createFromFormat will by default use todays day of the month (e.g. 17) if it is not specified. This means that a credit card could appear expired when it still has several days to go. If a card expires 06/20 (i.e. June 2020) then it actually stops working at 00:00:00 on 1st July 2020. The modify method fixes this. E.g.
$expiryTime = \DateTime::createFromFormat('my', $expiryMonth.$expiryYear, $timezone)->modify('+1 month first day of midnight');
The string '+1 month first day of midnight' does three things.
'+1 month' - add one month.
'first day of' - switch to the first day of the month
'midnight' - change the time to 00:00:00
The modify method is really useful for many date manipulations!
So to answer the op, this is what you need — with a slight adjustment to format to cater for single digit months:
$expiryMonth = 6;
$expiryYear = 20;
$timezone = new DateTimeZone('Europe/London');
$expiryTime = \DateTime::createFromFormat(
'm-y',
$expiryMonth.'-'.$expiryYear,
$timezone
)->modify('+1 month first day of midnight');
$currentTime = new \DateTime('now', $timezone);
if ($expiryTime < $currentTime) {
// Card has expired.
}
An addition to the above answers.
Be aware that by default the days will also be in the calculation.
For example today is 2019-10-31 and if you run this:
\DateTime::createFromFormat('Ym', '202111');
It will output 2021-12-01, because day 31 does not exist in November and it will add 1 extra day to your DateTime object with a side effect that you will be in the month December instead of the expected November.
My suggestion is always use the day in your code.
For op's question:
$y=15;
$m=05;
if(strtotime( substr(date('Y'), 0, 2)."{$y}-{$m}" ) < strtotime( date("Y-m") ))
{
echo 'card is expired';
}
For others with full year:
$y=2015;
$m=5;
if(strtotime("{$y}-{$m}") < strtotime( date("Y-m") ))
{
echo 'card is expired';
}
Would it not be simpler to just compare the string "201709" to the current year-month? Creating datetime objects will cost php some effort, I suppose.
if($_POST['expYear']. str_pad($_POST['expMonth'],2,'0', STR_PAD_LEFT ) < date('Ym')) {
echo 'expired';
}
edited as Adam states
The best answer is provided by John Conde above. It it does the minimum amount of processing: creates two correct DateTime objects, compares them and that's all it needs.
It could work also as you started but you must format the dates in a way that puts the year first.
Think a bit about it: as dates, 08/15 (August 2015) is after 12/14 (December 2014) but as strings, '08 15' is before '12 14'.
When the year is in front, even as strings the years are compared first and then, only when the years are equal the months are compared:
$expiryDate = $expiryDateTime->format('y m');
$currentDate = $currentDateTime->format('y m');
if ($expiryDate < $currentDate) {
echo 'Expired';
} else {
echo 'Valid';
}
Keep it simple, as the answer above me says except you need to string pad to the left:
isCardExpired($month, $year)
{
$expires = $year.str_pad($month, 2, '0', STR_PAD_LEFT);
$now = date('Ym');
return $expires < $now;
}
No need to add extra PHP load using DateTime
If you are using Carbon, which is a very popular Datetime extension library. Then this should be:
$expMonth = $_POST['month'];
$expYear = $_POST['year'];
$format_m_y = str_pad($expMonth,2,'0', STR_PAD_LEFT).'-'.substr($expYear, 2);
$date = \Carbon\Carbon::createFromFormat('m-y', $format_m_y)
->endOfMonth()
->startOfDay();
if ($date->isPast()) {
// this card is expired
}
Also take into consideration the exact date and time expiration:
Credit cards expire at the end of the month printed as its expiration date, not at the beginning. Many cards actually technically expire one day after the end of that month. In any case, unless they list a specific day of expiration along with month and year, they should work all the way through the end of their expiration month. Cardholders should not wait until the last moment to secure a replacement card. Source

PHP - Exclude all non-business hours / days from time difference

I have a table which shows the time since a job was raised.
// These are unix epoch times...
$raised = 1360947684;
$now = 1361192598;
$difference = 244914;
$difference needs to exclude any time outside of business hours (ex, 9-5 and weekends).
How could I tackle this?
The thing you have to do are 3 in numbers.
You take your start date and calculate the rest time on this day (if it is a business day)
You take your end date and calulate the time on this day and
you take the days in between and multiply them with your business hours (just those, that are business days)
And with that you are done.
Find a little class attached, which does those things. Be aware that there is no error handling, time zone settings, daylight saving time, ...
input:
start date
end date
output:
difference time in seconds
adjustable constants:
Business hours
Days that are not business days
Very bad idea, but I had no choice because I'm on php 5.2
<?php
date_default_timezone_set('Asia/Seoul');
$start = 1611564957;
$end = 1611670000;
$res = 0;
for($i = $start; $i<$end; $i++){
$h = date("H", $i);
if($h >= 9 && $h < 18){
//echo date("Y-m-d H:i:s", $i) . "<br>";
$res = $res + 1;
}
}
echo $res;
Use DateTime.
Using UNIX time for this is slightly absurd, and you would have to literally remake DateTime.
Look up relative formats where you can specify the hour on the day, e.g.
$date = new DateTime($raised);
$business_start = new DateTime("09:00"); // 9am today
$business_end = new DateTime("17:00"); // 5pm today
The rest is for you to work out.
Oh, and instead of start/end, you could probably use DateInterval with a value of P8H ("period 8 hours")
The problem with using timestamps directly is that you are assigning a context to a counter of seconds. You have to work backwards from the times you want to exclude and work out their timestamps beforehand. You might want to try redesigning your storage of when a job is raised. Maybe set an expiry time for it instead?

How to convert date into same format?

I want to get the $registratiedag and count a couple of days extra, but I always get stuck on the fact that it needs to be a UNIX timestamp? I did some google-ing, but I really don't get it.
I hope someone can help me figure this out. This is what I got so far.
$registratiedag = $oUser['UserRegisterDate'];
$today = strtotime('$registratiedag + 6 days');
echo $today;
echo $registratiedag;
echo date('Y-m-d', $today);
There's obviously something wrong with the strtotime('$registratiedag + 6 days'); part, because I always get 1970-01-01
You probably want this:
// Store as a timestamp
$registratiedag = strtotime($oUser['UserRegisterDate']);
$new_date = strtotime('+6 days', $registratiedag);
// You'll need to format for printing $new_date
echo date('Y-m-d', $new_date);
// I think you want to compare $new_date against
// today's date. I'd recommend a string comparison here,
// As time() includes the time as well
// time() is implied as the second argument to date,
// But we'll put it anyways just to be clearer
if( date('Y-m-d', $new_date) == date('Y-m-d', time()) ) {
// The dates are equal, do something here
}
else if($new_date < time()) {
// if the new date is earlier than today
}
// etc.
First it converts $registratiedag to a timestamp, then it adds 6 days
EDIT: You probably should change $today to something less misleading like $modified_date or something
try:
$today = strtorime($registratiedag);
$today += 86400 * 6; // seconds in 1 day * 6 days
at least one of your problems is that PHP does not expand variables in single quotes.
$today = strtotime("$registratiedag + 6 days");
//use double quotes and not single quotes when embedding a php variable in a string
If you want to include the value of variable $registratiedag right into the text passed as parameter of strtotime, you have to enclose that parameter with ", not with '.

Categories