Identify date-related text in a longer message - php

I'm currently writing a script that would extract all the dates from a message and convert them to timestamps. PHP's strtotime (similar to Unix's date -c 'some date') would be perfect for this, as it recognizes all kinds of dates, such as:
5pm today
2010-11-15 16:30
Thursday 8:00
However, I'm having trouble finding those dates in the first place. For example, in the following string,
I'll be there for dinner tomorrow at 9:00pm
I need to isolate "tomorrow at 9:00pm", as that's the part that strtotime recognizes.
Is there a regular expression or something similar that would return me all dates that can be parsed by strtotime?

The only thing I can think of is date_parse. A regular expression that matches any format accepted by strtotime would be huge.
An example of date_parse:
$str = "I'll be there for dinner tomorrow at 9:00pm";
$parsed = date_parse($str);
print_r($parsed);
It would output something like this (I removed the unimportant parts from it to make it the result lighter):
Array
(
[year] =>
[month] =>
[day] =>
[hour] => 21 // 9:00pm
[minute] => 0 // 9:00pm
[second] => 0 // 9:00pm
[fraction] => 0
[warning_count] => 1
[is_localtime] => 1
[zone_type] => 2
[zone] => -540
[is_dst] =>
[tz_abbr] => I
[relative] => Array
(
[year] => 0
[month] => 0
[day] => 1 // tomorrow (would be -1 for yesterday, etc.)
[hour] => 0
[minute] => 0
[second] => 0
)
)
Whether this works for you depends primarily on what your input looks like. If you have more than one instance of a date in your input string, it will not work as expected.

This might not be totally efficient, but should work for any date string that consists of up to 5 words in length. I would write the function, but I think you'll get the idea with the comments below...
$words = explode(' ',$original_string);
// Use the array_chunk() function break up this array into 1-word,
// 2-word, 3-word, and 4-word long substrings of the original string
// Reform them back into strings and pass each one through strtodate()

Related

How to convert this date format to PHP

From the JSON snippet that i got from a .net API query, I can't seem to convert the date /Date(1393477200000)/ properly in PHP.
I tried to do echo date('m/n/Y','1393477200000'); but it is still outputting the wrong date which is 07/7/46127 instead of the correct date of 2/27/2014.
Array
(
[status] => ok
[results] => Array
(
[0] => Array
(
[PROJECT_ID] => 1
[COMPANY_ID] => 1
[PROJECT_NAME] => The "Getting Started" Project
[PROJECT_NUMBER] => 000001
[CAN_OPEN_PROJECT] => 1
[DATE_START_DATE] => /Date(1393477200000)/
[DATE_END_DATE] => /Date(1440648000000)/
[PROJECT_DESC] =>
[TASK_NUMBER] => 6
[DATE_CREATED] => /Date(1409142925980)/
[TOTAL_TASKS] => 1
[TOTAL_INCOMPLETE_TASKS] => 1
[TOTAL_COMPLETED_TASKS] => 0
Any ideas how to format [DATE_START_DATE] correctly in PHP? Thanks!
Divide your unix-timestamp by 1000, then use date(..).
$date = '1393477200000';
echo date("m/d/y", $date/1000);
Its that simple.
Result:
02/27/14
echo date('m/d/Y',(1393477200000/1000)); U have to truncate last 3 digit.
The time received is in milliseconds... You have to divide by a thousand to retrieve UNIX epoch time:
echo date('m/d/Y',(1393477200000/1000));
And here is the fiddle

Using regular expressions to match a time interval

I'm having problems on how to preg_match this time statement.
TF 02:30 pm-04:00 am
I was able to separate the time into the array but I also want to get the AM and PM as well as the letter T and F.
This is for a class schedule module that I am working on. The data I got from the database is that string. I want to separate them so that I can manipulate the entries for the calendar that I have.
Here's what I have at this point.
$sampleString = 'T 02:30 pm-04:00 am';
$pattern = '/([0-1]?\d|2[0-9]):([0-5]?\d)/';
preg_match_all($pattern,$sampleString,$time);
print_r($time);
The output:
Array (
[0] => Array (
[0] => 02:30
[1] => 04:00 )
[1] => Array (
[0] => 02
[1] => 04 )
[2] => Array (
[0] => 30
[1] => 00 )
)
Thanks.
As recommended by IMSoP, splitting this up into parts makes it easier (looking again, I think your hour regex could use improvement, as it will accept hours from 0-29, I've changed it to 0?[1-9]|1[0-2] instead, to accept only 1 - 12)
Days: [MTWHFS]+
Space: \s
Hour: 0?[1-9]|1[0-2]
Colon: :
Minute: [0-5]?\d
Space: \s
am/pm: [ap]m
hyphen: -
Hour: 0?[1-9]|1[0-2]
Colon: :
Minute: [0-5]?\d
Space: \s
am/pm: [ap]m
Then just put them together, surrounding the desired capturing groups with parentheses:
([MTWHFS]+)\s(0?[1-9]|1[0-2]):([0-5]?\d)\s([pa]m)-(0?[1-9]|1[0-2]):([0-5]?\d)\s([pa]m)

php strtotime some day un complete

I have some date, like:
20 November 06:10
12 November 08:12
10 October 13:23
There all in the past 6 months, Now I want to strtotime() them, but they are all un complete (lack of year), how to make some process so that I could strtotime() them?
Try this:
$dates = array("10 October 13:23", "12 November 08:12", "10 October 13:23");
foreach($dates as $d){
$exploded = explode(" ", $d);
$newDate = array_slice($exploded, 0,2,true)+array(2=>"2012")+array(3 => $exploded[2]);
//print_r($newDate);
$time = strtotime(implode($newDate));
echo $time."<br/>";
}
The output i got is:
1349868180
1352704320
1349868180
The logic is:
You lack the year, so I exploded the dates into an array to slice them, insert the year (the +array(2=>"2012") part) and glue them again with implode, and then run the strtotime.
This work only for this year, so you can use this logic to add the year to all your dates, or in the future there will be absolutely no way to filter dates from different years.
I added the dates into an array for loop through all of them, you can use the loop other ways, depending on where you have all your dates stored. For example if they are in a database you can include the script in the while($row = mysqli_fetch_assoc($result)) part where $d would be $row['date'] instead.
You should use the DateTime class and its createFromFormat and getTimeStamp methods instead of strtotime.
print_r(date_parse_from_format("d F H:i", '20 November 06:10'));
gives you:
Array
(
[year] =>
[month] => 11
[day] => 20
[hour] => 6
[minute] => 10
[second] => 0
[fraction] =>
[warning_count] => 0
[warnings] => Array
(
)
[error_count] => 0
[errors] => Array
(
)
[is_localtime] =>
)

remove zero occurrence in array

I am implementing a function to calculate date. the function makes the calculations to find each element: year, month, week, day, hour, minute, second.
the result of the calculation is an array like this:
array (
[year] => 0
[month] => 0
[week] => 0
[day] => 0
[hour] => 3
[minute] => 193
[second] => 11583
)
must now remove any occurrence that is KEY = 0, and leave only the indices hour, minute, second.
there's some native PHP function that can do this?
Thank you all
array_filter ( array $input);
Should work. It will delete all elements with value equals to false.
If you would like all elements that are === 0 create your own callback function for array_filter like in the link below.
http://php.net/manual/en/function.array-filter.php

Two idential datetimes; one shows 12 hour the other 24 hour

I have a form with two datetime fields. The user inputs the date (yyyy-mm-dd) and time (3 boxes; hour, minute, am/pm).
For some reason, the first one isn't getting saved as a 24 hour time.
The following data is the result of entering:
2011-1-1
4:30 PM
I am using strtotime() to convert a string to a datetime format.
$dateOccured = date('Y-m-d H:i:s', strtotime($dateOccurred));
$dateResolved = date('Y-m-d H:i:s', strtotime($dateResolved));
If I use print_r() to look at the results of this, it is showing correctly.
Date Occurred:
[year] => 2011
[month] => 1
[day] => 1
[hour] => 16
[minute] => 30
[second] => 0
[fraction] => 0
[warning_count] => 0
Date Resolved
[year] => 2011
[month] => 1
[day] => 1
[hour] => 16
[minute] => 30
[second] => 0
[fraction] => 0
[warning_count] => 0
Both show the correct time: 16:30 (or 4:30PM). When I look in my database, this is what is shown.
Date Occurred
2011-01-01 04:30:00
Date Resolved
2011-01-01 16:30:00
I know it's a problem with the dateOccurred variable because if I replace it with dateResolved in my query, it gets inserted correctly. What I can't figure out is where the problem is? What am I missing that is causing this?
Thank you.
If it was the database, wouldn't replacing the dateOccurred variable with dateResolved in the query not matter?
Here is the INSERT query
"INSERT INTO
incidents (
incidentNumber, date, itFunction, issue, severity,
owner, dateOccurred, dateResolved, locationsImpacted, businessImpact,
rcaRequired, rcaReceived, rootCause, notes)
VALUES (
'{$incidentNumber}', '{$date}', '{$itFunction}', '{$issue}', '{$severity}',
'{$owner}', '{$dateOccurred}', '{$dateResolved}', '{$locationsImpacted}', '{$businessImpact}',
'{$rcaRequired}', '{$rcaReceived}', '{$rootCause}', '{$notes}')"
They are both datetime fields.
Found the problem...typos! I've been bashing my head against the wall for an hour trying to figure this out! $dateOccured (single R...rrrrrr)! Put this one in the embarrassing column.
I learned that error reporting can be made more useful by using
error_reporting(E_ALL | E_NOTICE)
Thanks to Chronial for that.

Categories