Get hours out of a datetime - php

Trying to get the hours in 24 hours format from a datetime and nothing works:
$date=date_create("now");
date_add($date,date_interval_create_from_date_string('3 hours'));
$finalDate = date_format($date,"Y-m-d H:i:s");
// $finalDate is "2013-12-25 15:06:45"
Tried the following:
date('H', $finalDate)); // getting 02
date('G', $finalDate)); // getting 02
$finalDate->hours); // getting nothing
date_format($finalDate,"H")); // getting nothing
Read all posts in this site, nothing solved it for me...

$date is already an DateTime object.
All you need to do is:
$hour = date_format($date, 'H');
or
$hour = $date->format('H');
PS: Object oriented style is recommended over Procedural style.

With DateTime and "object syntax":
<?php
$date = new DateTime();
$date->modify('+3 hours');
echo $date->format('H');
?>

Please use the newer DateTime object. I also added the out commented variant of how to see the difference between two different DateTime objects.
$date1 = new DateTime('2013-12-15 12:00:00');
$date2 = new DateTime('2013-12-25 13:30:30');
//$interval = $date1->diff($date2);
//$diff = $interval->format('%d');
//echo $diff;
echo $date1->format('H');
You can use the PDO variant of $date->add() to write what you did a little cleaner :)

Try this:
$timeStr=strtotime($finalDate);
echo date('H', $timeStr);

Related

Setting Php and Mysql timestamp

I need to set timestamp eg. 4 hours ahead and 2 hours ahead separately
In my database, I have their columns as timestamp.
I know I could do something similar to this but am not sure if it's correct.
// For 4 hours ahead of time
$dt2 = date("Y-m-d 04:i:s");
//For 2 days ahead
$dt2 = date("Y-m-02 H:i:s");
//For 4 hours ahead of time
$dt2 = date("Y-m-d H:i:s", strtotime('+4 hours'));
//For 2 days ahead of time
$dt2 = date("Y-m-d H:i:s", strtotime('+2 days'));
In my mind it's much better to work with DateTime field and the DateTime class.
You have the ability so modify that objects very easily. For example:
$aktDate = new \DateTime();
Now you have the actual date and time in an object. If you want you can put a string insight the DateTime function so set your date manually.
$aktDate = new \DateTime('Y-m-d 04:i:s');
Not you can modify your dates if you want with the modify function.
in your case:
$pastDate = clone $aktDate;
$pastDate->modify('+2 days');
$futureDate = clone $aktDate;
$futureDate->modify('+4 days');
if($pastDate < $aktDate && $aktDate < $futureDate) {
// do something
}
I like the DateTime function much more because it's readable and you can work directly with your DateTime fields from your MySQL database if you have such fields. You can write that example much shorter but so you have better readability.
$date = new DateTime('now');
$date->modify('+2 days');
echo $date->format('Y-m-d H:i:s');
$date = new DateTime('now');
$date->modify('+4 hours');
echo $date->format('Y-m-d H:i:s');
You need to use the strtotime() function (http://php.net/manual/en/function.strtotime.php).
For your examples:
//+2 hours<br>
strtotime("+2 hours");
// +2 days<br>
strtotime("+2 days")
Edit: for what you ask, about posted values, the syntax is like this:
strtotime("+2".$_POST['field_name']." days");
You can use hours/days/months/weeks/years and either + or -

save sql datetime to php variables

$date =$row2['DeliveryDate'];
$date now contains the date variable as a datetime, to display it I would use:
echo date_format($date, 'm-d-y');
the problem I'm having is extracting single values from $date for example:
$datetime = strtotime($row2['DeliveryDate']);
$mysqldate = date("d", $datetime);
returns this error:
Warning: strtotime() expects parameter 1 to be string, object given in
C:\xampp\htdocs\tutorials\DerBlatt\hebrewDateTrial.php on line 10
I've tried numerous ways to extract the day/month/year into single variables but nothing works
if someone can suggest a way it might work I'll be very greatfull;
I've copy/pasted code from many sites but all of them use an example of the date as a string, unfortunately i haven't found a solution for the datetime variable.
I wanna do something like:
$date =$row2['DeliveryDate'];
//whatever conversion code that comes in between.
$d = //the day from datetime
$m = //the month from datetime
$y = //the year from datetime
If you are using PHP 5.3 or better ,use the DateTime class .
if you want to display in this format $format='m-d-y';
Retrieving data from database .
$date =$row2['DeliveryDate'];
$date = DateTime::createFromFormat('Y-m-d H:i:s',$date);
if($date){ // if the date is correct
$yourdate = $date->format($format);
$year = $date->format('Y');
$month = $date->format('m');
$day = $date->format('d');
}
Saving to database .
$date = DateTime::createFromFormat($format,$date);
if($date){
$date = $date->format('Y-m-d H:i:s');
$row2['DeliveryDate'] = $date;
}else{
$row2['DeliveryDate'] = date('Y-m-d H:i:s');
}
Try this:
echo date('d',strtotime($row2['DeliveryDate']));
i think it will work.
so this is how i made it work (very funny)...
$m = date_format($row2['DeliveryDate'], 'm');
$d = date_format($row2['DeliveryDate'], 'd');
$y = date_format($row2['DeliveryDate'], 'y');
echo 'Month: '.$m.' Day: '.$d.' Year: '.$y;
Thank you guys for helping me, sometimes my best solution is just using my head...

strtotime with variable using php - object given

This is my current code:
$dateGame = new DateTime();
date_modify($dateGame, "+$universeTime Year");
$arrivalTime = date('Y-M-d H:i:s', strtotime("+$flightTimeMin minutes", $dateGame));
This isn't working because I believe "$dateGame" is an object. How would I turn it into something readable by "strtotime"?
Thanks
You dont need to use strtotime() since you are using datetime and you can use datetime object to format the date as
$universeTime = 3 ;
$flightTimeMin = 20;
$dateGame = new DateTime();
date_modify($dateGame, "+$universeTime Year +$flightTimeMin minutes");
If you want to format the display you can use as
echo $dateGame->format('Y-m-d H:i:s');
or just use
echo $dateGame->date ;

PHP - add 1 day to date format mm-dd-yyyy

<?php
$date = "04-15-2013";
$date = strtotime($date);
$date = strtotime("+1 day", $date);
echo date('m-d-Y', $date);
?>
This is driving me crazy and seems so simple. I'm pretty new to PHP, but I can't figure this out. The echo returns 01-01-1970.
The $date will be coming from a POST in the format m-d-Y, I need to add one day and have it as a new variable to be used later.
Do I have to convert $date to Y-m-d, add 1 day, then convert back to m-d-Y?
Would I be better off learning how to use DateTime?
there you go
$date = "04-15-2013";
$date1 = str_replace('-', '/', $date);
$tomorrow = date('m-d-Y',strtotime($date1 . "+1 days"));
echo $tomorrow;
this will output
04-16-2013
Documentation for both function
date
strtotime
$date = DateTime::createFromFormat('m-d-Y', '04-15-2013');
$date->modify('+1 day');
echo $date->format('m-d-Y');
See it in action
Or in PHP 5.4+
echo (DateTime::createFromFormat('m-d-Y', '04-15-2013'))->modify('+1 day')->format('m-d-Y');
reference
DateTime::createFromFormat()
$date = strtotime("+1 day");
echo date('m-d-y',$date);
use http://www.php.net/manual/en/datetime.add.php like
$date = date_create('2000-01-01');
date_add($date, date_interval_create_from_date_string('1 days'));
echo date_format($date, 'Y-m-d');
output
2000-01-2
The format you've used is not recognized by strtotime(). Replace
$date = "04-15-2013";
by
$date = "04/15/2013";
Or if you want to use - then use the following line with the year in front:
$date = "2013-04-15";
Actually I wanted same alike thing,
To get one year backward date, for a given date! :-)
With the hint of above answer from #mohammad mohsenipur
I got to the following link, via his given link!
Luckily, there is a method same as date_add method, named date_sub method! :-)
I do the following to get done what I wanted!
$date = date_create('2000-01-01');
date_sub($date, date_interval_create_from_date_string('1 years'));
echo date_format($date, 'Y-m-d');
Hopes this answer will help somebody too! :-)
Good luck guys!

PHP: add seconds to a date

I have $adate; which contains:
Tue Jan 4 07:59:59 2011
I want to add to this date the following:
$duration=674165; // in seconds
Once the seconds are added I need the result back into date format.
I don't know what I'm doing, but I am getting odd results.
Note: both variables are dynamic. Now they are equal to the values given, but next query they will have different values.
If you are using php 5.3+ you can use a new way to do it.
<?php
$date = new DateTime();
echo $date->getTimestamp(). "<br>";
$date->add(new DateInterval('PT674165S')); // adds 674165 secs
echo $date->getTimestamp();
?>
Just use some nice PHP date/time functions:
$adate="Tue Jan 4 07:59:59 2011";
$duration=674165;
$dateinsec=strtotime($adate);
$newdate=$dateinsec+$duration;
echo date('D M H:i:s Y',$newdate);
Given the fact that $adate is a timestamp (if that's the case), you could do something like this:
$duration = 674165;
$result_date = strtotime(sprintf('+%d seconds', $duration), $adate);
echo date('Y-m-d H:i:s', $result_date);
// add 20 sec to now
$duration = 20;
echo date("Y-m-d H:i:s", strtotime("+$duration sec"));
Do this:
$seconds = 1;
$date_now = "2016-06-02 00:00:00";
echo date("Y-m-d H:i:s", (strtotime(date($date_now)) + $seconds));
$current_time_zone = 150;
date("Y-m-d H:i:s",strtotime(date("Y-m-d H:i:s"))+$current_time_zone);
I made this example for a timezone, but if you change some parts it may help you out:
$seconds_to_add = 30;
$time = new DateTime();
$time->setTimezone(new DateTimeZone('Europe/London'));
$time2 = $time->format("Y/m/d G:i:s");
$time->add(new DateInterval('PT' . $seconds_to_add . 'S'));
$timestamp = $time->format("Y/m/d G:i:s");
echo $timestamp;
echo '========';
echo $time2;
Result:
2018/06/17 3:16:23========2018/06/17 3:15:53
It would be easier with DateTime::modify
(new DateTime($str))->modify("+$duration seconds"); //$str is the date in string
I have trouble with strtotime() to resolve my problem of add dynamic data/time value in the current time
This was my solution:
$expires = 3600; //my dynamic time variable (static representation here)
$date = date_create(date('Y-m-d H:i:s')); //create a date/time variable (with the specified format - create your format, see (1))
echo date_format($date, 'Y-m-d H:i:s')."<br/>"; //shows the date/time variable without add seconds/time
date_add($date, date_interval_create_from_date_string($expires.' seconds')); //add dynamic quantity of seconds to data/time variable
echo date_format($date, 'Y-m-d H:i:s'); //shows the new data/time value
font: https://secure.php.net/manual/en/datetime.add.php (consult Object Oriented style too, the Elzo Valugi solution)
(1) https://secure.php.net/manual/en/function.date.php

Categories