Converting string to time in PHP - php

I am having some trouble trying to convert string to time.
My Code is:
$time = strtotime("14 November, 2013 2:30 AM");
echo $time ."<br />";
echo date("m/d/Y", $time);
I know that strtotime is not magic, and I checked out the acceptable date/time formats but I am not sure how to convert the string to another string without converting it to time first.
What's the easiest way to accomplish this?

Take a look at DateTime::createFromFormat and then call format on the created DateTime instance.
Something like:
$yourTimeString = '14 November, 2013 2:30 AM';
$date = DateTime::createFromFormat('d F, Y h:i A', $yourTimeString);
echo $date->format('m/d/Y');

One way is to rewrite the string using explode and list.
<?php
// here we assume "day month, year time AMPM"
$date = "14 November, 2013 2:30 AM";
// assign a variable to each part of the string
list($day,$month,$year,$time,$ampm) = explode(" ",$date);
// remove the commas at the end of the month
$month = str_replace(',','',$month);
// Now we rewrite the strtotime string
$time = strtotime($month . " " . $day . ", " . $year . " " . $time . " " . $ampm);
echo $time ."<br />";
echo date("m/d/Y", $time);

Php date() function allow natural language string for parsing date,
for Ex:
echo date("d-M-Y", strtotime("first monday of 2019-07")); // returns first monday of july 2019
echo date("d-M-Y", strtotime("last sat of July 2008"));
You can find here php instructions to parsing date as natural languages.
http://php.net/manual/en/datetime.formats.relative.php

Related

Converting date (with milliseconds) into timestamp

I have date format like '25 May 2016 10:45:53:567'.
I want to convert into the time stamp.
strtotime function returns empty.
$date = '25 May 2016 10:45:53:567';
echo strtotime($date);
// returns empty
When I removed the milliseconds, it's working.
$date = '25 May 2016 10:45:53';
echo strtotime($date);
// returns 1464153353
Please sort out my issue. Thanks in advance.
Use DateTime:
$date = DateTime::createFromFormat('d M Y H:i:s:u', '25 May 2016 10:45:53:000');
echo $date->getTimestamp();
// 1464165953
// With microseconds
echo $date->getTimestamp().'.'.$date->format('u');
// 1464165953.000000
Split string:
$date = '25 May 2016 10:45:53:001';
preg_match('/^(.+):(\d+)$/i', $date, $matches);
echo 'timestamp: ' . strtotime($matches[1]) . PHP_EOL;
echo 'milliseconds: ' . $matches[2] . PHP_EOL;
// timestamp: 1464162353
// milliseconds: 001
Use Datetime instead of date and strtotime.
//using date and strtotime
$date = '25 May 2016 10:45:53:000';
echo "Using date and strtotime: ".date("Y-m-d H:i:s.u", strtotime($date));
echo "\n";\
//using DateTime
$date = new DateTime();
$date->createFromFormat('d M Y H:i:s.u', '25 May 2016 10:45:53:000');
echo "Using DateTime: ".$date->format("Y-m-d H:i:s.u");
// since you want timestamp
echo $date->getTimestamp();
// Output
// Using date and strtotime: 1969-12-31 16:00:00.000000
// Using DateTime: 2016-05-28 03:25:22.000000
Example

Find next occurrence of date

I want to find the next occurrence of date from the current date.
For example, imagine I want to find 20th of the month from current date
If current date is 10th october then return the result 2014-10-20 (Y-m-d)
If current date is 22nd october then return the result 2014-11-20 (Y-m-d)
I created a solution just now using a while loop.
$oldd= "2014-06-20";
$newdate = date("Y-m-d",strtotime($oldd."+1months"));
while(strtotime($newdate) <= strtotime(date("Y-m-d")))
{
$newdate = date("Y-m-d",strtotime($newdate."+1months"));
}
echo $newdate;
manually and pass that to strtotime(). The time information you need to extract from the reference time string. Like this:
$refdate = '2014-02-25 10:30:00';
$timestamp = strtotime($refdate);
echo date('Y-m-d H:i:s',
strtotime("next Thursday " . date('H:i:s', $timestamp), $timestamp)
);
same results could be achieved using string concatenation:
echo date('Y-m-d', strtotime("next Thursday", $timestamp)
. ' ' . date('H:i:s', $timestamp);
another way, you can use methods of DateTime object, PHP has really rich API in dealing with date time.
$current_date = new DateTime('2014-06-20');
if ($current_date->format('d') >= 20) {
// $current_date->modify('last day of this month')->modify("+20 days");
$current_date->modify('first day of next month')->modify("+19 days");
}else{
$current_date->modify('first day of this month')->modify("+19 days");
}
echo $current_date->format("Y-m-d");
http://php.net/manual/en/datetime.modify.php
http://php.net/manual/en/datetime.formats.relative.php

PHP get next occurrence of Monday from a certain date (with time)

I'm looking for the next Thursday after a specific date, say 2014-02-25. The problem I'm having here is that when I use the below code, the time seems to be erased.
<?php
$timestamp = '2014-02-25 10:30:00';
echo date('Y-m-d H:i:s', strtotime("next Thursday", strtotime($timestamp)));
?>
The result I am getting is 2014-02-27 00:00:00 when I would like it to be 2014-02-27 10:30:00
Is there something I am missing here that is causing the time to be set to midnight?
I appreciate the help, thanks.
There is no time format that can directly express this. You need to produce a format like
next Thursday 10:30:00
... manually and pass that to strtotime(). The time information you need to extract from the reference time string. Like this:
$refdate = '2014-02-25 10:30:00';
$timestamp = strtotime($refdate);
echo date('Y-m-d H:i:s',
strtotime("next Thursday " . date('H:i:s', $timestamp), $timestamp)
);
The same results could be achieved using string concatenation:
echo date('Y-m-d', strtotime("next Thursday", $timestamp)
. ' ' . date('H:i:s', $timestamp);
The documentation for so called relative time formats can be found here

need help converting time string to usable format

I have a string in the following format
yyyy-mm-dd-hh-mm-ss
The reason its in this format is because its part of a URL. I need help converting it to a usable time format in PHP.
Here is what I have tried so far.
$time = "2013-04-14-23-33-17";
$time2 = strtotime($time);
$time3 = date('M d, Y', $time2) . ' ' . _('at') . ' ' . date('h:i a', $time2);
echo $time3;
It just echos out Jan 01, 1970 at 12:00 am which is wrong instead of Apr 14, 2013 at 11:33 pm.
It doesn't work because that's not a valid date format. See Supported Date and Time Formats.
What you need to do is create a DateTime object by specifing a format for your string.
DateTime::createFromFormat does exactly that.
You could use DateTime to help you with the parsing:
$date = DateTime::createFromFormat('Y-m-d-H-i-s', $time);
echo $date->format('M d, Y h:i a');

PHP - Adding 7 days to a date the proper way [duplicate]

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

Categories