Converting string to formatted date using PHP - php

I've the following string:
$str = "Tuesday, February 21 at 7:30am at Plano B";
The at Plano B is optional. I would like to convert it to: TUE 21 FEB 07:30

$str = "Tuesday, February 21 at 7:30am at Plano B";
$time = strtotime(trim(substr($str,0,(strrpos("at"))));
echo "Date: " . strtoupper(date('D d M H:i', $time));
What do you mean by "at Plano B is optional". Is it sometimes there, sometimes not?
Otherwise:
$str = "Tuesday, February 21 at 7:30am at Plano B";
preg_match("/[a-z]+, ([a-z]+ [0-9]{1,2}) at ([0-9]{1,2}:[0-9]{1,2}[am|pm])/i", $str, $match);
$time = strtotime($match[1] + ' ' + $match[2]);
echo "Date: " . strtoupper(date('D d M H:i', $time));
Is it always either "Plano B" or empty? or can it also be "Plano A" or something completely diffrent?
See here: http://regexr.com?2vvuj
But you are missing the year in the initial string, so can't parse as strtotime. Also you want output without am/pm.. Do you want to use 24 hour time?
This is not a pretty way, but without the year, i dont think we have much choice..
preg_match("/([a-z]+), ([a-z]+) ([0-9]{1,2}) at ([0-9]{1,2}:[0-9]{1,2})([am|pm])/i", $str, $match);
$day = substr($match[1], 0, 3);
$mon = substr($match[2], 0, 3);
echo strtoupper($day . " " . $match[3] . " " . $mon . " " . $match[4]);

I'd like to propose a slightly different solution based on the not as oftenly used strptime. It uses a pre-defined format to parse the string.
Example:
<?php
// Specify a default timezone just in case one isn't set in php.ini.
date_default_timezone_set('America/Vancouver');
$str = "Tuesday, February 21 at 7:30am at Plano B";
if ($time = strptime($str, '%A, %B %e at %l:%M%P')) {
// This will default to the current year.
echo strtoupper(date('D d M H:i', mktime($time['tm_hour'], $time['tm_min'], 0, $time['tm_mday'], $time['tm_mon'])));
}
Output:
SUN 01 SEP 07:30

// Strip the last at, if its not a time
if(!preg_match("/at [0-9]+:[0-9]+[ap]m$/", $str)) {
$str = preg_replace("/at [^0-9].*/","",$str);
}
// Then convert to time
$time = strtotime($str);
// Then output in specified format
echo strtoupper(date("D d M h:i", $time));

Related

strtotime in PHP for dd MM yyyy

While trying:
echo "<br />".$opening_time = "02 May 2019 - 03:10";
echo "<br />".$closing_time = "12 May 2019 - 13:40";
echo "<br />".$string_opening_time = strtotime($opening_time);
echo "<br />".$string_closing_time = strtotime($closing_time);
echo "<br />".$diffrence_time = $string_closing_time - $string_opening_time;
The results are:
02 May 2019 - 03:10 12
May 2019 - 13:40
//2 blank lines
0
Why it is blank when I convert it to strtotime?
The format d M Y - H:i is not recognized, but you can recreate it as a DateTime object if you know what format it will be in using DateTime::createFromFormat().
Create two DateTime objects and use the diff() method on them, that will give you the difference.
$opening_time = "02 May 2019 - 03:10";
$closing_time = "12 May 2019 - 13:40";
$open = DateTime::createFromFormat("d M Y - H:i", $opening_time);
$close = DateTime::createFromFormat("d M Y - H:i", $closing_time );
$diff = $open->diff($close);
echo $opening_time."<br />\n";
echo $closing_time."<br />\n";
echo $diff->d." days ".$diff->h." hours ".$diff->m." minutes ";
Live demo at https://3v4l.org/3pKr4
If you need the difference in seconds, use the getTimestamp() methods.
$open = DateTime::createFromFormat("d M Y - H:i", $opening_time);
$close = DateTime::createFromFormat("d M Y - H:i", $closing_time );
$diff = $close->getTimestamp() - $open->getTimestamp();
echo $opening_time."<br />\n";
echo $closing_time."<br />\n";
echo $diff;
Live demo at https://3v4l.org/ZG5LJ

How to find current time of a region from a old time string in php?

I am getting time string from some mails date header. I need to get how much second before the mail has been sent to user.
Here is my code that I am trying to solve the problem.
<?php
//time string found in mail date header
$time_string = 'Wed, 15 Nov 2017 14:50:53 -0800 (PST)';
//when i use 'D, j M Y G:i:s O (e)' as identifier then date_create_from_format returns false
$mail_date = explode(" ", $time_string);
unset($mail_date[6]);
$dt_in = date_create_from_format('D, j M Y G:i:s O', implode(" ", $mail_date));
$time_in = strtotime(date_format($dt_in, 'd-m-Y H:i:s')) ; // This time may be according to my time zone (that is wrong need according to that time zone '-0800')
//returns time zone that is not compatible with php
$time_zone = date_format($dt_in, 'T'); //returns GMT-0800
//rest of the code not working
date_default_timezone_set($time_zone); //date_default_timezone_set(): Timezone ID 'GMT-0800' is invalid
$difference = time()-$time_in;
print_r($difference);
?>
It is not impotent to correct this code or do it like this. All I need to get the time difference. Any solution will be appreciable. Thanks in advance.
Convert date from email to a timestamp and compare with the current timestamp:
$time_string = 'Wed, 15 Nov 2017 14:50:53 -0800 (PST)';
$mail_date = explode(" ", $time_string);
unset($mail_date[6]);
$mail_datetime = date_create_from_format('D, j M Y G:i:s O', implode(" ", $mail_date));
$time_diff_in_seconds = time() - $mail_datetime->getTimestamp();

Extract date from string + PHP

Hello I am tring to get date "8 January 2014" from given string.
Wednesday, 8 January 2014 at 17:40
It will be good if you can use preg_replace?
PHP strtotime is bad at understanding the word "at" so this code should work and not return 1970:
$date = date("d F Y", strtotime(str_replace('at ','',"Wednesday, 8 January 2014 at 17:40")));
echo $date;
You can change the format just as you want; just change the letter d F Y and the list of letter that returns different values can be found in the manual.
Just made solution with explode() function:
$str = "Wednesday, 8 January 2014 at 17:40";
$ex1 = explode(", ", $str);
$ex2 = explode(" at", $ex1[1]);
$value = $ex2[0];
echo $value;
The DateTime class makes your life simpler !
<?php
$date = DateTime::createFromFormat('l, j F Y \a\t G:i','Wednesday, 8 January 2014 at 17:40');
echo $date->format('j F Y'); //"prints" 8 January 2014
Try regex pattern like this:
$str = 'Wednesday, 8 January 2014 at 17:40';
$date = preg_replace('/\w+,\s([a-zA-Z0-9\s]+)\sat\s([0-9:]+)/i', '$1', $str);
echo $date;
Here is simple code to get 8 January 2014 for you :)
<?php
$txt = 'Wednesday, 8 January 2014 at 17:40';
preg_match('#(?<=,\s)\d{1,2}\s\w+\s\d{1,4}(?=\sat)#', $txt, $result);
?>

Converting string to time in 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

Format a date string in PHP

If I have a string which represents a date, like "2011/07/01" (which is 1st July 2011) , how would I output that in more readable forms, like:
1 July 2011
1 Jul 2011 (month as three letters)
And also, how could I make it intelligently show date ranges like "2011/07/01" to "2011/07/11" as
1 - 11 July 2001
(without repeating the 'July' and '2011' in this case)
You can convert your date to a timestamp using strtotime() and then use date() on that timestamp. On your example:
$date = date("j F Y", strtotime("2011/07/01")); // 1 July 2011
$date = date("j M Y", strtotime("2011/07/01")); // 1 Jul 2011
As NullUserException mentioned, you can use strtotime to convert the date strings to timestamps. You can output 'intelligent' ranges by using a different date format for the first date, determined by comparing the years, months and days:
$date1 = "2011/07/01";
$date2 = "2011/07/11";
$t1 = strtotime($date1);
$t2 = strtotime($date2);
// get date and time information from timestamps
$d1 = getdate($t1);
$d2 = getdate($t2);
// three possible formats for the first date
$long = "j F Y";
$medium = "j F";
$short = "j";
// decide which format to use
if ($d1["year"] != $d2["year"]) {
$first_format = $long;
} elseif ($d1["mon"] != $d2["mon"]) {
$first_format = $medium;
} else {
$first_format = $short;
}
printf("%s - %s\n", date($first_format, $t1), date($long, $t2));
As for the second one:
$time1 = time();
$time2 = $time1 + 345600; // 4 days
if( date("j",$time1) != date("j",$time2) && date("FY",$time1) == date("FY",$time2) ){
echo date("j",$time1)." - ".date("j F Y",$time2);
}
Can be seen in action here
Just make up more conditions
I would use strtotime AND strftime. Is a much simpler way of doing it.
By example, if a have a date string like "Oct 20 18:29:50 2001 GMT" and I want to get it in format day/month/year I could do:
$mystring = "Oct 20 18:29:50 2001 GMT";
printf("Original string: %s\n", $mystring);
$newstring = strftime("%d/%m/%Y", strtotime($mystring));
printf("Data in format day/month/year is: %s\n", $newstring);

Categories