I need to add 24 hours to a date that will be stored in a variable.
Example:
$date = "2019-11-20 05:05:00"; => $date = "2019-11-21 05:05:00"; (24 hours have been added).
I've tried some options, but I haven't been successful in any of them.
I have tried with strtotime() method:
$new_time = date("Y-m-d H:i:s", strtotime('+24 hours')).
If the sintaxe is like above, then it works, but it doesn't seem to accept a pre-defined date or a variable, like this:
$date = "2019-11-20 05:05:00";
$new_time = date($date, strtotime('+24 hours'));
Or this:
$new_time = date("2019-11-20 05:05:00", strtotime('+24 hours'));
In both cases the output is the same as the input date, without the +24 being added.
I've experimented the modify() method.
$date = "2019-11-20 05:05:00";
$dateTime= new DateTime($date);
$dateTime->modify('+24 hours');
print_r($dateTime);
echo $datetime->date;
Output (if I print the objetct):
DateTime Object
(
[date] => 2019-11-21 05:05:00.000000
[timezone_type] => 3
[timezone] => Europe/Paris
)
2019-11-21 05:05:00.000000
Output (if I don't print the objetct):
Notice: Undefined property: DateTime::$date
It sort of works, but the problem is that I can access the date property only if I print the whole dateTime object, what would trouble my application. Besides that, apparently, these properties don't really exist, they seem to be more like a bug, since they are not described in the documentation as properties of the dateTime object.
I am trying to use getTimestamp(), but I couldn't add time to it.
How could I do that?
The PHP manual has a complete example;
<?php
$date = new DateTime('2000-01-01');
$date->add(new DateInterval('P1D'));
echo $date->format('Y-m-d') . "\n";
The value for DateInterval could be changed In 'PT24H'. During daylight savings changes 24 hours is not the same as 1 day, which PHP will arrange for you with the proper timezone configuration.
If you're working with DateTime object, all you have to do is create an interval and then use add method. Like so:
$dateTime = new DateTime();
$interval = new DateInterval("P0Y0M0DT24H0M0S");
$dateTime->add($interval);
Related
I'm trying to calculate the difference between 2 dates: $now and $old to get -> how long as past since old datetime.
$current_date = time();
$old= new DateTime($dateTimeString);
$now= new DateTime($current_date);
$interval = $now->diff($old);
I was trying with these values: 2016-02-23 02:15:43 --- 2016-02-22 21:45:11 and the result was more than 14hours of difference. I print the result like this:
$interval->format('%i Hours ago.');
$interval->format('%d Days ago.');
What I am doing wrong please?
The problem is here:
$current_date = time();
$now = new DateTime($current_date);
The value returned by time() is the number of seconds since 1970-01-01 00:00:00 UTC. The DateTime constructor tries to interpret it as a date that uses one of the usual date formats, it fails and produces a DateTime objects initialized with 0 (i.e. 1970-01-01 00:00:00 UTC).
If you want to create a new DateTime object from an Unix timestamp (the value returned by time() you can use DateTime::createFromFormat()
$current_time = time();
$now = DateTime::createFromFormat('U', $current_time);
Or you can pass the timestamp prefixed with '#' to DateTime::__construct():
$current_time = time();
$now = new DateTime('#'.$current_time);
This format is explained in the Compound date/time formats page.
But the easiest way to create a DateTime object that contains the current date and time is to either pass 'now' as argument to the constructor or omit it altogether:
$now1 = new DateTime('now');
$now2 = new DateTime();
The two DateTime objects constructed above should be identical (there is a small chance they are 1-second apart, though) and they both must contain the current date & time.
I'm being passed a date string (most likely in ISO8601 format) and need to convert it to the date of the ISO week to store as a DATETIME column in MySQL. To initialize the DateTime object the I want to save, I'm doing the following:
$date = new DateTime("now");
$date = new DateTime( $date->format("o-\WW") );
echo $date->format(DateTime::ISO8601) . "\n";
Since I'm using Doctrine2, I need to pass my entity a DateTime object. Is there a way to avoid making 2 DateTime objects to get the same result? Should I drop back to the date function and use that as the argument to the DateTime constructor?
$date = new DateTime( date("o-\WW", strtotime("now") );
You could use setISODate to update the first DateTime object using the week and year of the object via format():
$date = new DateTime();
$date->setISODate($date->format('o') , $date->format('W'));
echo $date->format(DateTime::ISO8601);
You could use modify() method of DateTime object.
$date = new DateTime();
$date->modify('sunday this week');
echo $date->format(DateTime::ISO8601) . "\n";
Note that if you want the first day of the week to be something other than Sunday, you will likely need to do something like the following. This example considers Monday as the first day of the week, thus for dates on a Sunday, you would need to get the date of the Monday from the previous week.
$date = new DateTime();
if ($date->format('D') === 'Sun') {
$date->modify('monday last week');
} else {
$date->modify('monday this week');
}
echo $date->format(DateTime::ISO8601) . "\n";
You can probably use date like this:
$date = new DateTime( date('o-\WW') );
Though that formatting looks a bit strange. :p You can of course also use some other method/function the class has to offer to change/modify the date.
I'm trying to 1) set a variable to the current date 2) format it as Y-m-d and 3) modify it to find a date 7 days in the past.
Here is the code I'm using to do this:
$date = new DateTime(); // get current date
$date->format('Y-m-d'); // format it
$wow_date = $date->modify('-7 days'); // find 7 days before current date
When I run this I get a 500 error code and haven't been able to troubleshoot why this is happening. Would greatly appreciate if someone could point me in the right direction.
UPDATE
Thanks for the help / comments. Here is what I've ended up going with:
$date = new DateTime(null, new DateTimeZone('America/Los_Angeles')); // get current date
$m_date = $date->format('Y-m-d'); // set it in format I need for queries
$wow_date = $date->modify('-7 days'); // get 7 days before
$m_wow_date = $wow_date->format('Y-m-d'); // format earlier date
If you want to use object oriented style, try this
$date->sub(new DateInterval('P7D'));
This is from php.net
Answered in this SO thread:
$date = date('Y-m-d', strtotime('-7 days'));
Or with DateTime class:
$date = new DateTime('7 days ago');
echo $date->format('Y-m-d');
If your final goal is a variable of type String containing the formatted date a week ago, then you can do it all in one line:-
$formattedDate = (new \DateTime())->modify('-7 days')->format('Y-m-d');
echo $formattedDate;
See it working
You need to configure default timezone for your application.
Try to find it on your php.ini uncomment or add this lines:
[Date]
; Defines the default timezone used by the date functions
date.timezone = "America/Los_Angeles"
Or via php script before use DateTime Class:
date_default_timezone_set('America/Los_Angeles');
Find your desired timezone at PHP MANUAL
I have this string object in my php array
"2013-03-05 00:00:00+00"
I would like to add 12 hours to the entry within PHP, then save it back to string in the same format
I believe this involves converting the string to a date object. But I'm not sure how smart the date object is and if I need to tell it formatting parameters or if it is supposed to just take the string
$date = new DateTime("2013-03-05 00:00:00+00");
$date->add("+12 hours");
//then convert back to string or just assign it to a variable within the array node
I was getting back empty values from this method or a similar one I tried
How would you solve this issue?
Thanks, your insight is appreciated
Change add() to modify(). add() expects a DateInterval object.
<?php
$date = new DateTime("2013-03-05 00:00:00+00");
$date->modify("+12 hours");
echo $date->format("Y-m-d H:i:sO");
See it in action
Here's an example using a DateInterval object:
<?php
$date = new DateTime("2013-03-05 00:00:00+00");
$date->add(new DateInterval('PT12H'));
echo $date->format("Y-m-d H:i:sO");
See it in action
Change this line
$date->add("+12 hours");
with
$date->add(new DateInterval("PT12H"));
this will add 12 hours to your date
Look at the DateInterval constructor page to know how to build the DateInterval string
Use this to add hours,
$date1= "2014-07-03 11:00:00";
$new_date= date("Y-m-d H:i:s", strtotime($date1 . " +3 hours"));
echo $new_date;
If you have dynamic interval, this way will avoid errors of wrong format for $dateDiff:
$dateDiff = "12 hours";
$interval = DateInterval::createFromDateString($dateDiff);
$date = new DateTime("2013-03-05 00:00:00+00");
$date->add($interval);
echo $date->format("Y-m-d H:i:sO");
The server that I have my sited hosted is on PHP5.12.14, and I have an error when I run the DateTime object from PHP5.3
# DateTime::add — Adds an amount of days, months, years, hours, minutes and seconds to a DateTime object
$date = new DateTime($item_user['mem_updated']);
# add a day to the object
$date -> add(new DateInterval('P1D'));
the error,
Fatal error: Call to undefined method DateTime::add() in /homepages/xxx.php on line xx
So, I have look for the other solutions rather than sticking to PHP5.3's DateTime object. How can I write the code to replace the code above?
basically I have this date and time data (for instance - 2011-01-21 02:08:39) from the mysql database, and I just need to add 1 day or 24 hours to that date/time, then passing it into a function below,
$time_togo = time_togo($date -> format('Y-m-d H:i:s'));
thanks.
strtotime would work
$timestamp = strtotime($item_user['mem_updated']);
$time_togo = date("Y-m=d H:i:s", strtotime("+1 Day", $timestamp));
Here's an example:
$date = date('Y-m-d H:i:s');
$new_tstamp = strtotime($date.'+1WEEK');
$new_date = date('Y-m-d H:i:s', $new_tstamp);
In other words, strtotime lets you use date expressions like +1DAY, +1MONTH and so on.
The above will work for date string (e.g.: 2010-01-01). If your original date is a Unix timestamp, you can still use strtotime, although a bit differently:
$new_tstamp = strtotime('+1WEEK', $timestamp);