Setting Php and Mysql timestamp - php

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 -

Related

PHP zero out the time for a date and add 3 days

I'm looking for an elegant/efficient way to take out the time portion of a datetime in format 'Y-m-d H:i:s', and then add 3 days.
Currently the solution is:
date('Y-m-d 00:00:00', strtotime("+3 days", strtotime('2017-01-23 05:32:12')));
where 2017-01-23 05:32:12 is the date, and this correctly outputs 2017-01-26 00:00:00.
It just feels like there has to be a better way to do this.
Thanks
DateTime() offers several of ways to do this. None of them are any less verbose than your current method:
// Plain old DateTime()
$date = (new DateTime('2017-01-23 05:32:12'))->modify('+3 days')->format('Y-m-d 00:00:00');
// DateTme using DateInterval to add three days
$date = (new DateTime('2017-01-23 05:32:12'))->add(new DateInterval('P3D'))->format('Y-m-d 00:00:00');
// DateTime setting the date to midnight instead of using 00:00:00
$date = (new DateTime('2017-01-23 05:32:12'))->modify('+3 days')->modify('midnight')->format('Y-m-d H:i:s');
If the date is today you can shorten this a bit:
$date = (new DateTime('+3 days'))->format('Y-m-d 00:00:00');
you can use DateTime class
$date = new DateTime('2017-01-23 05:32:12');
$date->modify('+3 days');
$outputDateString = $date->format('Y-m-d 00:00:00');
one line:
$date = ( new DateTime('2017-01-23 05:32:12'))->modify('+3 days')->format('Y-m-d 00:00:00');

date_create function is not working in php

I have an issue.I need to calculate the time difference but here the date_create function is not showing any output in php.I am explaining my code below.
while($row=mysqli_fetch_assoc($orderqry)){
$exit_date=$row['delivered_datetime'];
if($exit_date!=='0000-00-00 00:00:00'){
$deldate=date_create($exit_date);
$today=date_create(date('Y-m-d H:i:s'));
echo $today;exit;
$interval = date_diff($deldate, $today);
$hours = $interval->format('%h');
}
}
Here i am trying to echo $today but its not giving any result.Here i need to calculate the time difference in hour.In my DB i have existing time in the format of date('Y-m-d H:i:s').Please help me.
$today is DateTime instance. To echo it you need to call its format() method.
echo $today->format('Y-m-d H:i:s');
date_create is an alias of: DateTime::__construct(). see below example, I have assigned 6 Hour ago date in $exit_date. so ideally difference from current date should be 6 Hour.
$exit_date = date('Y-m-d H:i:s', strtotime('-6 Hours'));
$deldate=date_create($exit_date); //returns datetime class object
$today=date_create(date('Y-m-d H:i:s'));
$interval = date_diff($deldate, $today);
echo $hours = $interval->format('%h'); // output 6 hours
If you want to print date from $today variable then use:
echo $today->format('Y-m-d H:i:s'); //output: today's date in Y-m-d H:i:s format
for more detail have a look at http://php.net/manual/en/book.datetime.php

build a new mysql variable from an existing date field

I have a date column in my MySQL table and I want to build a new variable from that whereby I will add a few days.
example:
$date = 2014-12-12
now I need a second variable $date2 whereby the date will be 2014-12-17
So I need something like this
$date2 = $date + 5 days
I've searched for this and I got solutions for building queries, but I want to have a second variable. Is this possible?
I tried this (with no luck)
$date2 = DateTime::createFromFormat('d-m-Y', $date1);
$date2->modify('5 day');
echo $date2->format('Y-m-d');
This should work:
$date2 = strtotime($date) + (60*60*24*5); //convert date to unix time stamp and add 5 days
$date2 = date('Y-m-d', $date2); //convert back to readable format
Or an even better approach:
$date2 = date('Y-m-d', strtotime($date . "+5 days"));
You are missing the + in your modify call:
$date2 = DateTime::createFromFormat('d-m-Y', $date1);
$date2->modify('+5 day');
echo $date2->format('d-m-Y');

Adding minutes to date time in PHP

I'm really stuck with adding X minutes to a datetime, after doing lots of google'ing and PHP manual reading, I don't seem to be getting anywhere.
The date time format I have is:
2011-11-17 05:05: year-month-day hour:minute
Minutes to add will just be a number between 0 and 59
I would like the output to be the same as the input format with the minutes added.
Could someone give me a working code example, as my attempts don't seem to be getting me anywhere?
$minutes_to_add = 5;
$time = new DateTime('2011-11-17 05:05');
$time->add(new DateInterval('PT' . $minutes_to_add . 'M'));
$stamp = $time->format('Y-m-d H:i');
The ISO 8601 standard for duration is a string in the form of P{y}Y{m1}M{d}DT{h}H{m2}M{s}S where the {*} parts are replaced by a number value indicating how long the duration is.
For example, P1Y2DT5S means 1 year, 2 days, and 5 seconds.
In the example above, we are providing PT5M (or 5 minutes) to the DateInterval constructor.
PHP's DateTime class has a useful modify method which takes in easy-to-understand text.
$dateTime = new DateTime('2011-11-17 05:05');
$dateTime->modify('+5 minutes');
You could also use string interpolation or concatenation to parameterize it:
$dateTime = new DateTime('2011-11-17 05:05');
$minutesToAdd = 5;
$dateTime->modify("+{$minutesToAdd} minutes");
$newtimestamp = strtotime('2011-11-17 05:05 + 16 minute');
echo date('Y-m-d H:i:s', $newtimestamp);
result is
2011-11-17 05:21:00
Live demo is here
If you are no familiar with strtotime yet, you better head to php.net to discover it's great power :-)
You can do this with native functions easily:
strtotime('+59 minutes', strtotime('2011-11-17 05:05'));
I'd recommend the DateTime class method though, just posted by Tim.
I don't know why the approach set as solution didn't work for me.
So I'm posting here what worked for me in hope it can help anybody:
$startTime = date("Y-m-d H:i:s");
//display the starting time
echo '> '.$startTime . "<br>";
//adding 2 minutes
$convertedTime = date('Y-m-d H:i:s', strtotime('+2 minutes', strtotime($startTime)));
//display the converted time
echo '> '.$convertedTime;
I thought this would help some when dealing with time zones too. My modified solution is based off of #Tim Cooper's solution, the correct answer above.
$minutes_to_add = 10;
$time = new DateTime();
**$time->setTimezone(new DateTimeZone('America/Toronto'));**
$time->add(new DateInterval('PT' . $minutes_to_add . 'M'));
$timestamp = $time->format("Y/m/d G:i:s");
The bold line, line 3, is the addition. I hope this helps some folks as well.
A bit of a late answer, but the method I would use is:
// Create a new \DateTime instance
$date = DateTime::createFromFormat('Y-m-d H:i:s', '2015-10-26 10:00:00');
// Modify the date
$date->modify('+5 minutes');
// Output
echo $date->format('Y-m-d H:i:s');
Or in PHP >= 5.4
echo (DateTime::createFromFormat('Y-m-d H:i:s', '2015-10-26 10:00:00'))->modify('+5 minutes')->format('Y-m-d H:i:s')
If you want to give a variable that contains the minutes.
Then I think this is a great way to achieve this.
$minutes = 10;
$maxAge = new DateTime('2011-11-17 05:05');
$maxAge->modify("+{$minutes} minutes");
Use strtotime("+5 minute", $date);
Example:
$date = "2017-06-16 08:40:00";
$date = strtotime($date);
$date = strtotime("+5 minute", $date);
echo date('Y-m-d H:i:s', $date);
As noted by Brad and Nemoden in their answers above, strtotime() is a great function. Personally, I found the standard DateTime Object to be overly complicated for many use cases. I just wanted to add 5 minutes to the current time, for example.
I wrote a function that returns a date as a string with some optional parameters:
1.) time:String | ex: "+5 minutes" (default = current time)
2.) format:String | ex: "Y-m-d H:i:s" (default = "Y-m-d H:i:s O")
Obviously, this is not a fully featured method. Just a quick and simple function for modifying/formatting the current date.
function get_date($time=null, $format='Y-m-d H:i:s O')
{
if(empty($time))return date($format);
return date($format, strtotime($time));
}
// Example #1: Return current date in default format
$date = get_date();
// Example #2: Add 5 minutes to the current date
$date = get_date("+5 minutes");
// Example #3: Subtract 30 days from the current date & format as 'Y-m-d H:i:s'
$date = get_date("-30 days", "Y-m-d H:i:s");
one line mysql datetime format
$mysql_date_time = (new DateTime())->modify('+15 minutes')->format("Y-m-d H:i:s");
One more example of a function to do 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.)
// Return adjusted time.
function addMinutesToTime( $dateTime, $plusMinutes ) {
$dateTime = DateTime::createFromFormat( 'Y-m-d H:i', $dateTime );
$dateTime->add( new DateInterval( 'PT' . ( (integer) $plusMinutes ) . 'M' ) );
$newTime = $dateTime->format( 'Y-m-d H:i' );
return $newTime;
}
$adjustedTime = addMinutesToTime( '2011-11-17 05:05', 59 );
echo '<h1>Adjusted Time: ' . $adjustedTime . '</h1>' . PHP_EOL . PHP_EOL;
Without using a variable:
$yourDate->modify("15 minutes");
echo $yourDate->format( "Y-m-d H:i");
With using a variable:
$interval= 15;
$yourDate->modify("+{$interval } minutes");
echo $yourDate->format( "Y-m-d H:i");

adding 1 day to a DATETIME format value

In certain situations I want to add 1 day to the value of my DATETIME formatted variable:
$start_date = date('Y-m-d H:i:s', strtotime("{$_GET['start_hours']}:{$_GET['start_minutes']} {$_GET['start_ampm']}"));
What is the best way to do this?
There's more then one way to do this with DateTime which was introduced in PHP 5.2. Unlike using strtotime() this will account for daylight savings time and leap year.
$datetime = new DateTime('2013-01-29');
$datetime->modify('+1 day');
echo $datetime->format('Y-m-d H:i:s');
// Available in PHP 5.3
$datetime = new DateTime('2013-01-29');
$datetime->add(new DateInterval('P1D'));
echo $datetime->format('Y-m-d H:i:s');
// Available in PHP 5.4
echo (new DateTime('2013-01-29'))->add(new DateInterval('P1D'))->format('Y-m-d H:i:s');
// Available in PHP 5.5
$start = new DateTimeImmutable('2013-01-29');
$datetime = $start->modify('+1 day');
echo $datetime->format('Y-m-d H:i:s');
If you want to do this in PHP:
// replace time() with the time stamp you want to add one day to
$startDate = time();
date('Y-m-d H:i:s', strtotime('+1 day', $startDate));
If you want to add the date in MySQL:
-- replace CURRENT_DATE with the date you want to add one day to
SELECT DATE_ADD(CURRENT_DATE, INTERVAL 1 DAY);
The DateTime constructor takes a parameter string time. $time can be different things, it has to respect the datetime format.
There are some valid values as examples :
'now' (the default value)
2017-10-19
2017-10-19 11:59:59
2017-10-19 +1day
So, in your case you can use the following.
$dt = new \DateTime('now +1 day'); //Tomorrow
$dt = new \DateTime('2016-01-01 +1 day'); //2016-01-02
Use strtotime to convert the string to a time stamp
Add a day to it (eg: by adding 86400 seconds (24 * 60 * 60))
eg:
$time = strtotime($myInput);
$newTime = $time + 86400;
If it's only adding 1 day, then using strtotime again is probably overkill.
You can use
$now = new DateTime();
$date = $now->modify('+1 day')->format('Y-m-d H:i:s');
You can use as following.
$start_date = date('Y-m-d H:i:s');
$end_date = date("Y-m-d 23:59:59", strtotime('+3 days', strtotime($start_date)));
You can also set days as constant and use like below.
if (!defined('ADD_DAYS')) define('ADD_DAYS','+3 days');
$end_date = date("Y-m-d 23:59:59", strtotime(ADD_DAYS, strtotime($start_date)));
I suggest start using Zend_Date classes from Zend Framework. I know, its a bit offtopic, but I'll like this way :-)
$date = new Zend_Date();
$date->add('24:00:00', Zend_Date::TIMES);
print $date->get();
Using server request time to Add days. Working as expected.
25/08/19 => 27/09/19
$timestamp = $_SERVER['REQUEST_TIME'];
$dateNow = date('d/m/y', $timestamp);
$newDate = date('d/m/y', strtotime('+2 day', $timestamp));
Here '+2 days' to add any number of days.
One liner !
echo (new \DateTime('2016-01-01 +1 day'))->format('Y-m-d H:i:s');

Categories