I am working on a php code as shown below in which I want to extract time from DateTime object.
Here is the php code:
$timestamp = new \DateTime($episode->air_date, new \DateTimeZone('America/New_York'));
$new_timestamp = clone $timestamp;
print_r($new_timestamp); // Line A
Line A above prints:
DateTime Object ( [date] => 2019-11-14 23:00:00.000000 [timezone_type] => 3 [timezone] => America/New_York )
Problem Statement:
I am wondering what php code I need to add so that it extracts time (hr and mins only) from DateTime object.
In the php code above, I have added Line A for debugging purpose.
use format to get any format of your choosing.
$timestamp = new DateTime();
$new_timestamp = clone $timestamp;
print_r($new_timestamp->format('H:i:s')); // 16:30:52
You can use the DateTime::format method, as answered by Gavin. Or, if you're more familiar with strftime's format specifiers, or just need its generally-better locale-sensitivity, you can use it instead:
php > $timestamp = new DateTime();
php > print_r(strftime('%T', $timestamp->getTimestamp()));
16:38:29
Related
What is the "cleanest" way to add a date and a time string in PHP?
Albeit having read that DateTime::add expects a DateInterval, I tried
$date = new \DateTime('17.03.2016');
$time = new \DateTime('20:20');
$result = $date->add($time);
Which was no good and returned nothing to $result.
To make a DateInterval from '20:20', I only found very complex solutions...
Maybe I should use timestamps?
$date = strtotime($datestring);
$timeObj = new \DateTime($timestring);
// quirk to only get time in seconds from string date
$time = $timeObj->format('H') * 3600 + $timeObj->format('i') * 60 + $timeObj->format('s');
$datetime = $date+$time;
$result = new \DateTime;
$result->setTimestamp($datetime);
In my case, this returns the desired result, with the correct timezone offset. But what do you think, is this robust? Is there a better way?
If you want to add 20 hours and 20 minutes to a DateTime:
$date = new \DateTime('17.03.2016');
$date->add($new \DateInterval('PT20H20M'));
You do not need to get the result of add(), calling add() on a DateTime object will change it. The return value of add() is the DateTime object itself so you can chain methods.
See DateInterval::__construct to see how to set the intervals.
DateTime (and DateTimeImmutable) has a modify method which you could leverage to modify the time by adding 20 hours and 20 minutes.
Updated
I've included examples for both DateTime and DateTimeImmutable as per the comment made, you don't need to assign the outcome of modify to a variable because it mutates the original object. Whereas DateTimeImmutable creates a new instance and doesn't mutate the original object.
DateTime
<?php
$start = new DateTimeImmutable('2018-10-23 00:00:00');
echo $start->modify('+20 hours +20 minutes')->format('Y-m-d H:i:s');
// 2018-10-23 20:20:00
Using DateTime: https://3v4l.org/6eon8
DateTimeImmutable
<?php
$start = new DateTimeImmutable('2018-10-23 00:00:00');
$datetime = $start->modify('+20 hours +20 minutes');
var_dump($start->format('Y-m-d H:i:s'));
var_dump($datetime->format('Y-m-d H:i:s'));
Output
string(19) "2018-10-23 00:00:00"
string(19) "2018-10-23 20:20:00"
Using DateTimeImmutable: https://3v4l.org/oRehh
I have a date:
$launched=new DateTime();
I would like to create a new DateTime using $launched but adding days. Something like:
$expired=new DateTime($launched->modify("+$expiry days"));
How can I do this?
Assuming you are using PHP 5.5 or newer DateTimeImmutable makes this easy:
$launched = new DateTimeImmutable();
$expired = $launched->modify("+$expiry days");
DateTimeImmutable does not modify the original object which is what DateTime does. So you can just assign the resulting object return by modify() to a variable and have a new object with a date in the future.
If you are using an older, and obsolete, version of PHP you can clone the original object to achieve the same result:
$launched = new DateTimeImmutable();
$expired = clone $launched;
$expired->modify("+$expiry days");
I' am trying to convert the date of next 7 days into timestamp so that I can compare against my date timestamp in database to get some results.
This function is used to get the next 7 days from today
$next_date = date("d/m/Y", strtotime("7 day"))
Output
30/04/2014
Now I' am again running strtotime() on $next_date variable who holds the next 7days and converting to timestamp.
echo strtotime($next_date);
This is not working. I followed this stackoverflow answer and few others.
As an alternative suggestion you could look at PHP's internal DateTime() and DateInterval() classes. It makes it a bit easier to convert between formats and do date/time addition and subtraction imho. DateInterval requires at least PHP version 5.3.
An example:
// create a current DateTime
$currDate = new DateTime();
// copy the current DateTime and
// add an interval of 7 days
$nextDate = clone $currDate;
$nextDate->add(new DateInterval('P7D'));
// both objects are easily converted to timestamps
echo $currDate->getTimestamp(); // e.g: 1398296728
echo $nextDate->getTimestamp(); // e.g: 1398901528
// and both can be easily formatted in other formats
echo $currDate->format('d/m/Y'); // e.g: 24/04/2014
echo $nextDate->format('d/m/Y'); // e.g: 01/05/2014
EDIT
For completeness, here's another example of how you can add seven days to a DateTime object:
$now = new DateTimeImmutable();
$then = $now->modify('+7 days');
var_dump($now->format('Y-m-d'), $then->format('Y-m-d'));
Yields:
string(10) "2016-05-24"
string(10) "2016-05-31"
You can also use DateTime - the difference in this use case is that DateTime::modify() will modify the instance $now where DateTimeImmutable::modify() will return a new DateTimeImmutable object - so if you need to create a new object whilst retaining the old one, it's probably the most succinct approach.
Hope this helps :)
http://www.php.net/manual/en/datetime.construct.php
http://www.php.net/manual/en/dateinterval.construct.php
Just store the value from strtotime first?
$timestamp_in_7_days = strtotime('7 day');
$next_date = date('d/m/Y', $timestamp_in_7_days);
There is no need to throw the time back and forth between unix timestamp and date-format.
I have been crawling through the web and trying to find a solution so I am coming here.
I have an MSSQL database and I am using PHP5.3 to connect and fetch data from one of the tables. The issue I am having has to do with dates.
$result = sqlsrv_query($conn, "SELECT TOP 10 * FROM TAData WHERE DateTime >= '2013-11-11T07:45:00.000'");
while($row = sqlsrv_fetch_array($result))
{
print_r ($row['DateTime']);
echo "<br />";
echo date("Y-m-d H:i:s", strtotime($row['DateTime']));
}
With the output looking like this:
DateTime Object ( [date] => 2013-11-11 07:46:08 [timezone_type] => 3 [timezone] => Africa/Johannesburg )
January 1, 1970, 2:00 am
All I need is a simple date and time (YYYY-MM-DD HH:MM) that I can use. Once I have it in any sort of format (or understand how it works), I can manipulate it from there. But it is not displaying in any functional way.
You cannot access property date on DateTime object, like in the other answer:
$dt = new DateTime();
echo $dt->date; # this will trigger Notice: Undefined property: DateTime::$date
Please don't use any strtotime() or date() functions, when you already have DateTime object! Just use method format() on DateTime object to format datetime, like:
echo $dt->format('Y-m-d H:i:s');
# or $row['DateTime']->format('Y-m-d H:i:s'); in your example
How in PHP do I get the regular timestamp format out of a MongoDB date?
Assume I have:
$my_date;
print_r($my_date);
The print_r output is:
MongoDate Object ( [sec] => 1346300336 [usec] => 593000 )
But doing:
echo $my_date;
Outputs:
0.59300000 1346300336
Even tried:
echo (string)$my_date
Same thing.
$my_date->sec is the unix timestamp, use date() function to show it in required format.
echo date('Y-m-d H:i:s', $my_date->sec);
Just a quick update, to say that MongoDate has a toDateTime method since the version 1.6 of the pecl extension.
You can now do
$mongoDate->toDateTime()->format(...)
you are missing the microsecond.
To show (mongo -> php)
$fecha = date(preg_replace('`(?<!\\\\)u`', $my_date->usec, 'Y-M-d H:i:s.u'), $my_date->sec);
//MongoDate ISODate("2013-05-28T15:27:24.735Z")
//Php Date 2013-May-28 10:27:24.735000
To send to mongo (php -> mongo)
$fecha_mongo = new MongoDate(strtotime($fecha));
//Fail function, the short way but, 70000 isn't equal to 700000.
//$fecha_mongo->usec = (int)$fecha_micro->format("u");
preg_match("/\.(.*)/", $fecha, $uSec);
$fecha_mongo->usec = (int)(count($uSec)==2?$uSec[1]:0);
//Php Date 2013-May-28 10:27:24.735000
//MongoDate ISODate("2013-05-28T15:27:24.735Z")
Good day!
Mario T.
First, create date from millisecond using given function:
public function showdatefn($mili)
{
$seconds = (string)$mili / 1000;
return date("d-m-Y", $seconds);
}
$date =$this->showdatefn(<put mongo date here>);
This will give you correct date.
Use MongoDB\BSON\UTCDateTime MongoDate is deprecated
$mongoDate = new \MongoDB\BSON\UTCDateTime(strtotime('2020-10-01 18:30:00'));