This question already has answers here:
Add hours to datetime in PHP
(1 answer)
How to add an hour onto the time of this datetime string?
(3 answers)
php string in a date format, add 12 hours
(4 answers)
Closed 1 year ago.
I'm trying to add four hours to a date but the resultant time is incorrect
$date = $dates[0] < $dates[1] ? $dates[1] : $dates[0];
$new_date = date("Y-m-d H:i:s", strtotime('+4 hours', $date));
echo $date;
echo "<br/>". $new_date;
The result i'm getting is
2015-09-17 09:36:18
1969-12-31 20:33:35
The first date is correct but the second isn't, it should be 4 hours ahead of the first
Does this work?
$date = $dates[0] < $dates[1] ? $dates[1] : $dates[0];
$new_date = date("Y-m-d H:i:s", strtotime('+4 hours', strtotime($date)));
echo $date;
echo "<br/>". $new_date;
You were passing $date AS the second argument of strtotime, and it's not a UNIX timestamp (as you said). So with strtotime again, you should convert it in a UNIX timestamp, and then pass it to strtotime.
Add timestamps to a timestamp, not to a date string.
echo date("Y-m-d H:i:s", strtotime('+4 hours', strtotime("2015-09-17 09:36:18")));
^
Fiddle
That is the right syntax. You can simplify it however with
echo date("Y-m-d H:i:s", strtotime('2015-09-17 09:36:18 +4 hours'));
Fiddle
You're using strtotime incorrectly. Its second argument MUSt be a unix timestamp:
php > var_dump(strtotime('+4 hours', 12345));
int(26745)
php > var_dump(strtotime('+4 hours', '2015-09-17 09:36:18'));
PHP Notice: A non well formed numeric value encountered in php shell code on line 1
int(16415)
Your call should be
php > var_dump(date('r', strtotime('2015-09-17 09:36:18 + 4 hours')));
^^^^^^^^^^^
string(31) "Thu, 17 Sep 2015 13:36:18 -0500"
php >
Both other answers are correct.
Not seeing what you have in your $dates array makes it a bit tricky to give exact answer :) but in the following example i assumed you have a well formatted string date, in which case you need to convert it back to the timestamp using same method (strtotime) before adding what you like into it .
$date = (new DateTime('now'))->format('Y-m-d H:i:s');
$new_date = date('Y-m-d H:i:s', strtotime('+4 hours', strtotime($date)));
echo $date . PHP_EOL . $new_date;
In other word, if your $date array contains UNIX time stamp then your original code should work
$date = (new DateTime('now'))->getTimestamp();
$new_date = date("Y-m-d H:i:s", strtotime('+4 hours', $date));
Related
I have a timestamp stored in a session (1299446702).
How can I convert that to a readable date/time in PHP? I have tried srttotime, etc. to no avail.
Use PHP's date() function.
Example:
echo date('m/d/Y', 1299446702);
strtotime makes a date string into a timestamp. You want to do the opposite, which is date. The typical mysql date format is date('Y-m-d H:i:s'); Check the manual page for what other letters represent.
If you have a timestamp that you want to use (apparently you do), it is the second argument of date().
I just added H:i:s to Rocket's answer to get the time along with the date.
echo date('m/d/Y H:i:s', 1299446702);
Output: 03/06/2011 16:25:02
$timestamp = 1465298940;
$datetimeFormat = 'Y-m-d H:i:s';
$date = new \DateTime();
// If you must have use time zones
// $date = new \DateTime('now', new \DateTimeZone('Europe/Helsinki'));
$date->setTimestamp($timestamp);
echo $date->format($datetimeFormat);
result: 2016-06-07 14:29:00
Other time zones:
Africa
America
Antarctica
Arctic
Asia
Atlantic
Australia
Europe
Indian
Pacific
Others
If you are using PHP date(), you can use this code to get the date, time, second, etc.
$time = time(); // you have 1299446702 in time
$year = $time/31556926 % 12; // to get year
$week = $time / 604800 % 52; // to get weeks
$hour = $time / 3600 % 24; // to get hours
$minute = $time / 60 % 60; // to get minutes
$second = $time % 60; // to get seconds
If anyone wants timestamp conversion directly to a DateTime object, there's a simple one-liner:
$timestamp = 1299446702;
$date = DateTime::createFromFormat('U', $timestamp);
Following #sromero comment, timezone parameter (the 3rd param in DateTime::createFromFormat()) is ignored when unix timestamp is passed, so the below code is unnecessary.
$date = DateTime::createFromFormat('U', $timestamp, new DateTimeZone('UTC'); // not needed, 3rd parameter is ignored
You may check PHP's manual for DateTime::createFromFormat for more info and options.
Try this one:
echo date('m/d/Y H:i:s', 1541843467);
$epoch = 1483228800;
$dt = new DateTime("#$epoch"); // convert UNIX timestamp to PHP DateTime
echo $dt->format('Y-m-d H:i:s'); // output = 2017-01-01 00:00:00
In the examples above "r" and "Y-m-d H:i:s" are PHP date formats, other examples:
Format Output
r ----- Wed, 15 Mar 2017 12:00:00 +0100 (RFC 2822 date)
c ----- 2017-03-15T12:00:00+01:00 (ISO 8601 date)
M/d/Y ----- Mar/15/2017
d-m-Y ----- 15-03-2017
Y-m-d H:i:s ----- 2017-03-15 12:00:00
Try it.
<?php
$timestamp=1333342365;
echo gmdate("Y-m-d\TH:i:s\Z", $timestamp);
?>
You can try this:
$mytimestamp = 1465298940;
echo gmdate("m-d-Y", $mytimestamp);
Output :
06-07-2016
Unless you need a custom date and time format, it's easier, less error-prone, and more readable to use one of the built-in date time format constants:
echo date(DATE_RFC822, 1368496604);
echo date("l M j, Y",$res1['timep']);
This is really good for converting a unix timestamp to a readable date along with day. Example:
Thursday Jul 7, 2016
echo 'Le '.date('d/m/Y', 1234567890).' à '.date('H:i:s', 1234567890);
I have used this:
<?php echo date('d/m/Y H:i a', $row['start_time']); ?>
I am trying to add minutes to current date but it returns strange results
date_default_timezone_set('Asia/Karachi');
$currentDate = date("m-d-Y H:i:s");
$currentDate_timestamp = strtotime($currentDate);
$endDate_months = strtotime("+10 minutes", $currentDate_timestamp);
$packageEndDate = date("m-d-Y H:i:s", $endDate_months);
echo " <br> " . $packageEndDate . " <br> ";
echo $currentDate;
I am getting Output
01-01-1970 05:50:00
07-19-2013 20:25:23
It should return
07-19-2013 20:35:23
07-19-2013 20:25:23
After this I need to query to database so date format should be same. Database column is of string type.
Your code is redundant. Why format a timestamp as a string, then convert that string back to a timestamp?
Try
$now = time();
$ten_minutes = $now + (10 * 60);
$startDate = date('m-d-Y H:i:s', $now);
$endDate = date('m-d-Y H:i:s', $ten_minutes);
instead.
Probably the minimalist way would be:
date_default_timezone_set('Asia/Baku');
$packageEndDate = date('Y-m-d H:i:s', strtotime('+10 minute'));
echo $packageEndDate;
Output (Current time in my city at the time of writing):
2017-07-20 12:45:17
Try this:
$now = time();
$tenMinFromNow = date("m-d-Y H:i:s", strtotime('+10 minutes', $time));
$tenMinsFromNow = (new \DateTime())->add(new \DateInterval('PT10M'));
Will leave you with a DateTime object representing a time 10 minutes in the future. Which will allow you to do something like:-
echo $tenMinsFromNow->format('d/m/Y H:i:s');
See it working
PHP version >= 5.4 I'm afraid, but you should be using at least that version by now anyway.
Pakistan, which is the localisation explicitly set, uses "DD-MM-YYYY" format dates so the problem occurs when you cast the date into a string of "MM-DD-YYYY". This American format of date is not parseable by the Pakistan localisation.
If you still want to keep the round-trip to a string and back, use DD-MM-YYYY or the ISO datetime format.
While this is the only (current) answer which actually explains your original issue, I recommend the code be refactored as others have demonstrated.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Getting time and date from timestamp with php
I am trying to convert this date format:
09/14/2012 10:11
into this other standard timestamp format:
2012-09-14 09:44:54
What is the most efficient way of doing it?
You can use PHP's date and strtotime functions:
$date = '09/14/2012 10:11';
$formatted = date('Y-m-d H:i:s', strtotime($date));
You can use DateTime object
$date = DateTime($myDate);
or your custom input format with createFromFormat
$date = DateTime::createFromFormat('d/m/y H:i:s', $myDate);
format Will make your output
$result = $date->format('Y-m-d H:i:s');
date('Y-m-d H:i:s', strtotime('09/14/2012 10:11'));
Though it's going to be hard to change the time.
Convert first into timestamp with strtotime and convert timestamp into date with date.
$outputDate = date( 'Y-m-d H:i:s', strtotime( $inputDate ));
I want to add number of days to current date:
I am using following code:
$i=30;
echo $date = strtotime(date("Y-m-d", strtotime($date)) . " +".$i."days");
But instead of getting proper date i am getting this:
2592000
Please suggest.
This should be
echo date('Y-m-d', strtotime("+30 days"));
strtotime
expects to be given a string containing a US English date format and will try to parse that format into a Unix timestamp (the number of seconds since January 1 1970 00:00:00 UTC), relative to the timestamp given in now, or the current time if now is not supplied.
while date
Returns a string formatted according to the given format string using the given integer timestamp or the current time if no timestamp is given.
See the manual pages for
http://www.php.net/manual/en/function.strtotime.php
http://www.php.net/manual/en/function.date.php
and their function signatures.
This one might be good
function addDayswithdate($date,$days){
$date = strtotime("+".$days." days", strtotime($date));
return date("Y-m-d", $date);
}
$date = new DateTime();
$date->modify('+1 week');
print $date->format('Y-m-d H:i:s');
or print date('Y-m-d H:i:s', mktime(date("H"), date("i"), date("s"), date("m"), date("d") + 7, date("Y"));
$today=date('d-m-Y');
$next_date= date('d-m-Y', strtotime($today. ' + 90 days'));
echo $next_date;
You can add like this as well, if you want the date 5 days from a specific date :
You have a variable with a date like this (gotten from an input or DB or just hard coded):
$today = "2015-06-15"; // Or can put $today = date ("Y-m-d");
$fiveDays = date ("Y-m-d", strtotime ($today ."+5 days"));
echo $fiveDays; // Will output 2015-06-20
Keep in mind, the change of clock changes because of daylight saving time might give you some problems when only calculating the days.
Here's a little php function which takes care of that:
function add_days($date, $days) {
$timeStamp = strtotime(date('Y-m-d',$date));
$timeStamp+= 24 * 60 * 60 * $days;
// ...clock change....
if (date("I",$timeStamp) != date("I",$date)) {
if (date("I",$date)=="1") {
// summer to winter, add an hour
$timeStamp+= 60 * 60;
} else {
// summer to winter, deduct an hour
$timeStamp-= 60 * 60;
} // if
} // if
$cur_dat = mktime(0, 0, 0,
date("n", $timeStamp),
date("j", $timeStamp),
date("Y", $timeStamp)
);
return $cur_dat;
}
You could also try:
$date->modify("+30 days");
You can do it by manipulating the timecode or by using strtotime(). Here's an example using strtotime.
$data['created'] = date('Y-m-d H:i:s', strtotime("+1 week"));
You can use strtotime()
$data['created'] = date('Y-m-d H:m:s', strtotime('+1 week'));
I know this is an old question, but for PHP <5.3 you could try this:
$date = '05/07/2013';
$add_days = 7;
$date = date('Y-m-d',strtotime($date) + (24*3600*$add_days)); //my preferred method
//or
$date = date('Y-m-d',strtotime($date.' +'.$add_days.' days');
You could use the DateTime class built in PHP. It has a method called "add", and how it is used is thoroughly demonstrated in the manual: http://www.php.net/manual/en/datetime.add.php
It however requires PHP 5.3.0.
$date = "04/28/2013 07:30:00";
$dates = explode(" ",$date);
$date = strtotime($dates[0]);
$date = strtotime("+6 days", $date);
echo date('m/d/Y', $date)." ".$dates[1];
You may try this.
$i=30;
echo date("Y-m-d",mktime(0,0,0,date('m'),date('d')+$i,date('Y')));
Simple and Best
echo date('Y-m-d H:i:s')."\n";
echo "<br>";
echo date('Y-m-d H:i:s', mktime(date('H'),date('i'),date('s'), date('m'),date('d')+30,date('Y')))."\n";
Try this
//add the two day
$date = "**2-4-2016**"; //stored into date to variable
echo date("d-m-Y",strtotime($date.**' +2 days'**));
//print output
**4-4-2016**
Use this addDate() function to add or subtract days, month or years (you will need the auxiliar function reformatDate() as well)
/**
* $date self explanatory
* $diff the difference to add or subtract: e.g. '2 days' or '-1 month'
* $format the format for $date
**/
function addDate($date = '', $diff = '', $format = "d/m/Y") {
if (empty($date) || empty($diff))
return false;
$formatedDate = reformatDate($date, $format, $to_format = 'Y-m-d H:i:s');
$newdate = strtotime($diff, strtotime($formatedDate));
return date($format, $newdate);
}
//Aux function
function reformatDate($date, $from_format = 'd/m/Y', $to_format = 'Y-m-d') {
$date_aux = date_create_from_format($from_format, $date);
return date_format($date_aux,$to_format);
}
Note: only for php >=5.3
Use the following code.
<?php echo date('Y-m-d', strtotime(' + 5 days')); ?>
Reference has found from here - How to Add Days to Current Date in PHP
Even though this is an old question, this way of doing it would take of many situations and seems to be robust. You need to have PHP 5.3.0 or above.
$EndDateTime = DateTime::createFromFormat('d/m/Y', "16/07/2017");
$EndDateTime->modify('+6 days');
echo $EndDateTime->format('d/m/Y');
You can have any type of format for the date string and this would work.
//Set time zone
date_default_timezone_set("asia/kolkata");
$pastdate='2016-07-20';
$addYear=1;
$addMonth=3;
$addWeek=2;
$addDays=5;
$newdate=date('Y-m-d', strtotime($pastdate.' +'.$addYear.' years +'.$addMonth. ' months +'.$addWeek.' weeks +'.$addDays.' days'));
echo $newdate;
Do not use php's date() function, it's not as accurate as the below solution and furthermore it is unreliable in the future.
Use the DateTime class
<?php
$date = new DateTime('2016-06-06'); // Y-m-d
$date->add(new DateInterval('P30D'));
echo $date->format('Y-m-d') . "\n";
?>
The reason you should avoid anything to do with UNIX timestamps (time(), date(), strtotime() etc) is that they will inevitably break in the year 2038 due to integer limitations.
The maximum value of an integer is 2147483647 which converts to Tuesday, 19 January 2038 03:14:07 so come this time; this minute; this second; everything breaks
Source
Another example of why I stick to using DateTime is that it's actually able to calculate months correctly regardless of what the current date is:
$now = strtotime('31 December 2019');
for ($i = 1; $i <= 6; $i++) {
echo date('d M y', strtotime('-' . $i .' month', $now)) . PHP_EOL;
}
You'd get the following sequence of dates:
31 December
31 November
31 October
31 September
31 August
31 July
31 June
PHP conveniently recognises that three of these dates are illegal and converts them into its best guess, leaving you with:
01 Dec 19
31 Oct 19
01 Oct 19
31 Aug 19
31 Jul 19
01 Jul 19
I want to add number of days to current date:
I am using following code:
$i=30;
echo $date = strtotime(date("Y-m-d", strtotime($date)) . " +".$i."days");
But instead of getting proper date i am getting this:
2592000
Please suggest.
This should be
echo date('Y-m-d', strtotime("+30 days"));
strtotime
expects to be given a string containing a US English date format and will try to parse that format into a Unix timestamp (the number of seconds since January 1 1970 00:00:00 UTC), relative to the timestamp given in now, or the current time if now is not supplied.
while date
Returns a string formatted according to the given format string using the given integer timestamp or the current time if no timestamp is given.
See the manual pages for
http://www.php.net/manual/en/function.strtotime.php
http://www.php.net/manual/en/function.date.php
and their function signatures.
This one might be good
function addDayswithdate($date,$days){
$date = strtotime("+".$days." days", strtotime($date));
return date("Y-m-d", $date);
}
$date = new DateTime();
$date->modify('+1 week');
print $date->format('Y-m-d H:i:s');
or print date('Y-m-d H:i:s', mktime(date("H"), date("i"), date("s"), date("m"), date("d") + 7, date("Y"));
$today=date('d-m-Y');
$next_date= date('d-m-Y', strtotime($today. ' + 90 days'));
echo $next_date;
You can add like this as well, if you want the date 5 days from a specific date :
You have a variable with a date like this (gotten from an input or DB or just hard coded):
$today = "2015-06-15"; // Or can put $today = date ("Y-m-d");
$fiveDays = date ("Y-m-d", strtotime ($today ."+5 days"));
echo $fiveDays; // Will output 2015-06-20
Keep in mind, the change of clock changes because of daylight saving time might give you some problems when only calculating the days.
Here's a little php function which takes care of that:
function add_days($date, $days) {
$timeStamp = strtotime(date('Y-m-d',$date));
$timeStamp+= 24 * 60 * 60 * $days;
// ...clock change....
if (date("I",$timeStamp) != date("I",$date)) {
if (date("I",$date)=="1") {
// summer to winter, add an hour
$timeStamp+= 60 * 60;
} else {
// summer to winter, deduct an hour
$timeStamp-= 60 * 60;
} // if
} // if
$cur_dat = mktime(0, 0, 0,
date("n", $timeStamp),
date("j", $timeStamp),
date("Y", $timeStamp)
);
return $cur_dat;
}
You could also try:
$date->modify("+30 days");
You can do it by manipulating the timecode or by using strtotime(). Here's an example using strtotime.
$data['created'] = date('Y-m-d H:i:s', strtotime("+1 week"));
You can use strtotime()
$data['created'] = date('Y-m-d H:m:s', strtotime('+1 week'));
I know this is an old question, but for PHP <5.3 you could try this:
$date = '05/07/2013';
$add_days = 7;
$date = date('Y-m-d',strtotime($date) + (24*3600*$add_days)); //my preferred method
//or
$date = date('Y-m-d',strtotime($date.' +'.$add_days.' days');
You could use the DateTime class built in PHP. It has a method called "add", and how it is used is thoroughly demonstrated in the manual: http://www.php.net/manual/en/datetime.add.php
It however requires PHP 5.3.0.
$date = "04/28/2013 07:30:00";
$dates = explode(" ",$date);
$date = strtotime($dates[0]);
$date = strtotime("+6 days", $date);
echo date('m/d/Y', $date)." ".$dates[1];
You may try this.
$i=30;
echo date("Y-m-d",mktime(0,0,0,date('m'),date('d')+$i,date('Y')));
Simple and Best
echo date('Y-m-d H:i:s')."\n";
echo "<br>";
echo date('Y-m-d H:i:s', mktime(date('H'),date('i'),date('s'), date('m'),date('d')+30,date('Y')))."\n";
Try this
//add the two day
$date = "**2-4-2016**"; //stored into date to variable
echo date("d-m-Y",strtotime($date.**' +2 days'**));
//print output
**4-4-2016**
Use this addDate() function to add or subtract days, month or years (you will need the auxiliar function reformatDate() as well)
/**
* $date self explanatory
* $diff the difference to add or subtract: e.g. '2 days' or '-1 month'
* $format the format for $date
**/
function addDate($date = '', $diff = '', $format = "d/m/Y") {
if (empty($date) || empty($diff))
return false;
$formatedDate = reformatDate($date, $format, $to_format = 'Y-m-d H:i:s');
$newdate = strtotime($diff, strtotime($formatedDate));
return date($format, $newdate);
}
//Aux function
function reformatDate($date, $from_format = 'd/m/Y', $to_format = 'Y-m-d') {
$date_aux = date_create_from_format($from_format, $date);
return date_format($date_aux,$to_format);
}
Note: only for php >=5.3
Use the following code.
<?php echo date('Y-m-d', strtotime(' + 5 days')); ?>
Reference has found from here - How to Add Days to Current Date in PHP
Even though this is an old question, this way of doing it would take of many situations and seems to be robust. You need to have PHP 5.3.0 or above.
$EndDateTime = DateTime::createFromFormat('d/m/Y', "16/07/2017");
$EndDateTime->modify('+6 days');
echo $EndDateTime->format('d/m/Y');
You can have any type of format for the date string and this would work.
//Set time zone
date_default_timezone_set("asia/kolkata");
$pastdate='2016-07-20';
$addYear=1;
$addMonth=3;
$addWeek=2;
$addDays=5;
$newdate=date('Y-m-d', strtotime($pastdate.' +'.$addYear.' years +'.$addMonth. ' months +'.$addWeek.' weeks +'.$addDays.' days'));
echo $newdate;
Do not use php's date() function, it's not as accurate as the below solution and furthermore it is unreliable in the future.
Use the DateTime class
<?php
$date = new DateTime('2016-06-06'); // Y-m-d
$date->add(new DateInterval('P30D'));
echo $date->format('Y-m-d') . "\n";
?>
The reason you should avoid anything to do with UNIX timestamps (time(), date(), strtotime() etc) is that they will inevitably break in the year 2038 due to integer limitations.
The maximum value of an integer is 2147483647 which converts to Tuesday, 19 January 2038 03:14:07 so come this time; this minute; this second; everything breaks
Source
Another example of why I stick to using DateTime is that it's actually able to calculate months correctly regardless of what the current date is:
$now = strtotime('31 December 2019');
for ($i = 1; $i <= 6; $i++) {
echo date('d M y', strtotime('-' . $i .' month', $now)) . PHP_EOL;
}
You'd get the following sequence of dates:
31 December
31 November
31 October
31 September
31 August
31 July
31 June
PHP conveniently recognises that three of these dates are illegal and converts them into its best guess, leaving you with:
01 Dec 19
31 Oct 19
01 Oct 19
31 Aug 19
31 Jul 19
01 Jul 19