php add hours to date output wrong result - php

Basically what I want to do is to send an email to follow up on order placed in 3 hours later.
What I try to do is to get the current date (up to hours level), then compare with the orderdate+ 3 hours, to see whether it match.
Example orderdate: 2010-06-12 18, after add 3 hours should become 2010-06-12 21
However, after add hour, the final result sometimes become bigger, sometimes become smaller... something wrong.
$now= date('Y-m-d H');
echo $now . "<br>";
...
...
while ($data = mysql_fetch_array ($result))
{
$orderid = $data['orderid'];
$orddate = $data['orddate'];
$corddate= date('Y-m-d H:i:s', $orddate);
$year = substr ($corddate, 0, 4);
$month = substr ($corddate, 5, 2);
$day = substr ($corddate, 8, 2);
$hour = substr ($corddate, 11, 2);
$actualorderdate= $year . "-" . $month . "-" . $day . " " . $hour;
$new_time = mktime ($hour+3, 0, 0, $month, $day, $year);
$year = date ('Y', $new_time);
$month = date ('m', $new_time);
$day= date ('d', $new_time);
$hour= date ('h', $new_time);
$xhourslater= $year . "-" . $month . "-" . $day . " " . $hour;
echo "actualorderdate: ". $actualorderdate. " xhourslater: " . $xhourslater. "<br>";
if($now==$xhourslater)
{
echo "now is 3 hours later" . "<br>";
//send email follow up, then update status as sent, in order not to resend anytime in the 3rd hour.
}
}

Seems to me like you're doing a lot of excess parsing for nothing.
$orddate = $data['orddate'];
$actualOrderDate = date('Y-m-d H:i:s', $orddate);
$timeToSendEmail = date('Y-m-d H:i:s', strtotime('+3 hours', $orddate)); //Assuming $orddate is a timestamp int. If not, you'll have to do some calculations or something there, possibly using date() again.
Basically, you just want to have the order time + 3 hours, so use php's strtotime (http://php.net/manual/en/function.strtotime.php) function. Very helpful.
If that's not what you want, please post some test data so it's easier to figure out what might be going funky.

I believe it's simpler to
$date_now = date( "Y-m-d g:i a" ); // get the date
$time_now = time( $date_now ); // convert it to time
$time_next = $time_now + 3 * 60 * 60; // add 3 hours (3 x 60mins x 60sec)
$date_next = date( "Y-m-d H", $time_next); // convert it back to date

Related

How to sum hours with existing datetime in PHP?

I have two fields which store data like 2018-03-26 11:20:35 and 02:25:10(2 hours 25 minutes and 10 seconds) first data is date and time. second one is only time. I want to sum it and finally my result should 2018-03-26 13:45:45
How to do that in php code?
I have tried this way:
<?php
$date = '2018-03-26 11:20:35';
//echo $date;
//echo "<br>";
$hours = '02:25:10'; /* this data dynamic */
$sumTime = strtotime($date) + strtotime($hours);
$new_time = date("Y-m-d H:i:s", $sumTime);
echo $new_time;
Output:
Warning: date() expects parameter 2 to be integer, float given in C:\my-project-path\test.php on line 7
Here's a simple solution, some checks are skipped:
// convert your date to DateTime object
$date = '2018-03-26 11:20:35';
$dt = new DateTime($date);
// convert your period to DateInterval
$hours = '02:25:10'; /* this data dynamic */
$parts = explode(':', $hours);
$interval = new DateInterval('PT' . (int)$parts[0] . 'H' . $parts[1] . 'M' . $parts[2] . 'S');
// Add interval to date
$dt->add($interval);
// Format date as you need
echo $dt->format('Y-m-d H:i:s');
You could create a duration in seconds by comparing today at "00:00:00" and today at $hours. Actually, strtotime($hours) returns the timestamp of today at $hours, so, the addition of the two timestamp don't give the expected result.
If $hours is lesser than 24 hours, you could use:
$date = '2018-03-26 11:20:35';
$hours = '02:25:10';
$d0 = strtotime(date('Y-m-d 00:00:00'));
$d1 = strtotime(date('Y-m-d ').$hours);
$sumTime = strtotime($date) + ($d1 - $d0);
$new_time = date("Y-m-d H:i:s", $sumTime);
echo $new_time;
Outputs:
2018-03-26 13:45:45
You should check DateTime::add:
http://php.net/manual/en/datetime.add.php
http://php.net/manual/en/datetime.examples-arithmetic.php
Example:
<?php
// Convert h:m:s format to PThHmMsS format
sscanf('02:25:10', '%d:%d:%d', $hour, $minute, $second);
$intervalSpec = sprintf('PT%dH%dM%dS', $hour, $minute, $second);
$datetime = new DateTimeImmutable('2018-03-26 11:20:35');
$newDatetime = $datetime->add (new DateInterval($intervalSpec));
echo $newDatetime->format(DateTime::W3C);
It could be done with some simple string manipulation:
$dt = new DateTime("$date UTC");
$modify = preg_replace('/:/', ' hours ', $hours, 1);
$modify = preg_replace('/:/', ' minutes ', $modify, 1);
$modify .= ' seconds';
$dt->modify($modify);
demo
If you have MySQL as your data storage, you could do:
DATE_ADD(field1, INTERVAL field2 HOUR_SECOND)
demo
you can do something like:
$hour = $hours->format('H'); //This way you get a string which contains the hours
$date->modify('+'.$hour.' hour'); //you modify your date adding the hours
I'm assuming you only need the hours, and not minutes and seconds
EDIT:
you can do like that using regexp
$date = new \DateTime('2018-03-26 11:20:35');
$hours ='02:25:10';
preg_match("/^([0-9].*):([0-9].*):([0-9].*)/",$hours,$matches);
$date->modify('+'.$matches[1].' hour');
$date->modify('+'.$matches[2].' minute');
echo $date->modify('+'.$matches[3].' second')->format('Y-m-d H:i:s');

Getting the Date and numeric weekday in PHP

i'm developing an application in PHP and I need to use dates and the numeric representation of weekdays.
I've tried the following:
$today = date("Y-m-d");
$number = date('N', strtotime($today));
echo "Today: " . $today . " weekday: " . $number . "<br>";
$today = strtotime($today);
$tomorrow = strtotime($today);
$tomorrow = strtotime("+1 day", $today);
$number2 = date('N', strtotime($tomorrow));
echo "Tomorrow: " . date('Y-m-d', $tomorrow) . " weekday: " . $number2 . "<br>";
Output
Today: 2016-11-11 weekday: 5
Tomorrow: 2016-11-12 weekday: 4
This isn't right because the weekday of tomorrow should be 6 instead of 4.
can someone help me out?
Using DateTime would provide a simple solution
<?php
$date = new DateTime();
echo 'Today: '.$date->format( 'Y-m-d' ) .' weekday '. $date->format( 'N' )."\n";
$date->modify( '+1 days' );
echo 'Tomorrow: '.$date->format( 'Y-m-d' ) .' weekday '. $date->format( 'N' )."\n";
Output
Today: 2016-11-11 weekday 5
Tomorrow: 2016-11-12 weekday 6
However the day numbers are slightly different, the N respresents the weekday number and as you can see Friday (Today) is shown as 5. With that Monday would be 1 and Sunday would be 7.
If you look at the example below you should get the same result
echo date( 'N' );
Output
5
Date Formatting - http://php.net/manual/en/function.date.php
You have little error in the code, here`s the working one:
$today = date("Y-m-d");
$number = date('N', strtotime($today));
echo "Today: " . $today . " weekday: " . $number . "<br>";
$today = strtotime($today);
$tomorrow = strtotime($today);
$tomorrow = strtotime("+1 day", $today);
$number2 = date('N', $tomorrow);
echo "Tomorrow: " . date('Y-m-d', $tomorrow) . " weekday: " . $number2 . "<br>";
DateTime is the Object Oriented method of working with dates in PHP. I find it to be working much more fluently. That aside, it looks alot better.
// Create a new instance
$now = new DateTime();
echo $now->format('N');
// Next day
$now->modify('+1 day');
echo $now->format('N');
Resources
DateTime manual - PHP.net
You almost have it right but not quite. Why are you using strtotime on $number2? Change it to $number2 = date('N', $tomorrow); and it will work.

Add weeks in decimal value in php

I am trying to add weeks in decimal values like 1.5, 2.5 to date through strtotime() function. But its not giving correct result. I am using it like:
$start_date = "2015-01-01";
$date = strtotime(date("Y-m-d", strtotime($start_date)) . " +3.5 weeks");
$date = date("Y-m-d",$date);
echo $date;
And its giving 2015-02-04 as output. When added non decimal values like:
$date = strtotime(date("Y-m-d", strtotime($start_date)) . " +3 weeks");
It gives perfect results.
Any thought on it?
$date = '2015-01-01';
$weeks = "2,3,4,4.5";
foreach(explode(",", $weeks) as $week) {
print $week."\n";
$hours = $week * 24 * 7;
print $hours."\n";
print date("Y-m-d", strtotime("{$date} +{$hours} hours"))."\n";
}
You can use this logic, multiply your week decimal or not like 1,2,2.5,3,3.5 and multiply it by the amount of hours in a week :
$week = 2.5;
$desired = '+ '.$week*168.' hours';
$date = strtotime($desired, $start_date);
However, why playing with strings when you can just play with hours or seconds integers and doing a simple addition ?

Combine date and time then add selected hours

I'm trying to add some hours to a date dynamically.
I have a date, time and hours variable.
$appdate is in the format of 2013/03/23
$time is in military time format 13:00:00
$rei equals hours but it's in a plain number format from 0-48.
I'm trying to combine the $appdate and the $time together then add the $rei hours selected to it to end with $reiexpires in standard mysql format. 2013-03-23 20:00:00
$reitime = date('H',strtotime($rei));
$reidate = date('Y-m-d H:i:s',strtotime($appdate.$time));
$reiexpires = date('Y-m-d H:i:s',strtotime($reidate + $reitime));
$appdate = "2013/03/23";
$time = "13:00:00";
$rei = 48;
$reitime = strtotime($appdate . " " . $time . " + " . $rei . " hours");
$reiexpires = date('Y-m-d H:i:s', $reitime);
echo $reiexpires;
Output:
2013-03-25 13:00:00

Using PHP date to display weekly dates

I'm not really sure what to call this. But basically I want to be able to have a user click on "Popular Stories from This Week", and it will take them to a page that will have other stuff but mainly the dates. For example, July 10-17.
I'm currently using this code:
$seven_days_ago = date('j') - 7;
$time_span = date('F ' . $seven_days_ago . ' - j');
Now, I ran into a problem when we entered July, because it would display something like July -3 - 4. I need a way for it to detect if the seven days ago variable is negative, and figure out what it should display. Help?
Thanks!
You can use strtotime for this:
$seven_days_ago = strtotime('-7 days');
$time_span = date('F j', $seven_days_ago) . ' - ' . date('F j');
The above gives me "June 28 - July 5" for $time_span.
you need to use strtotime
$timeago = strtotime("7 days ago");
What about using
$unix_timestamp = mktime(0, 0, 0, date("m"), date("d")-7, date("Y"));
and just take the returned unix timestamp?
Update
Just a little code snipped that will give you a full working example. However I don't like it that much :)
<?php
$today = date("d F");
list($today_day, $today_month) = explode(" ", $today);
$previous = date("d F", mktime(0, 0, 0, date("m"), date("d")-7, date("Y")));
list($previous_day, $previous_month) = explode(" ", $previous);
if($today_month != $previous_month){
echo $previous_month." ".$previous_day." - ".$today_month." ".$today_day;
}else{
echo $today_month." ".$previous_day." - ".$today_day;
}
die();
?>
i just created a very nifty little function. Just pass it the Week number, it returns you an array of that week's days dates.
function findWeekDates($weekNumber=null, $year=null ) {
// receives a specific Week Number (0 to 52) and returns that week's day dates in an array.
// If no week specified returns this week's dates.
$weekNumber = ($weekNumber=='') ? date('W'): $weekNumber ;
$year = ($year=='') ? date('Y'): $year ;
$weekNumber=sprintf("%02d", $weekNumber);
for ($i=1;$i<=7;$i++) {
$arrdays[] = strtotime($year.'W'.$weekNumber.$i);
}
return $arrdays;
}
Example Usage - find a given week start and end dates:
$week= (isset($_GET['week']) && $_GET['week'] !=='')? $_GET['week'] : date('W') ;
$year = (isset($_GET['year']) && $_GET['year'] !=='')? $_GET['year'] : date('Y') ;
if($week>52) {
$week = 1;
$year++;
}else if($week<1) {
$week=52;
$year--;
}
$week_days = findWeekDates($week, $year);
$starting_date = date('Y-m-d', $week_days[0]);
$ending_date = date('Y-m-d', $week_days[6]);
hope this helps...

Categories