Comparing times (with milliseconds and without dates) - php

I'm parsing subtitle files (srt format) and here's an example of a line of dialogue:
27
00:01:32,400 --> 00:01:34,300
Maybe they came back
for Chinese food.
The times come in the format
hours:minutes:seconds,milliseconds
I want to manipulate these times and do comparisons but the various PHP classes I've come across don't seem to have support for milliseconds.
My problem:
One thing I want to do is parse 2 subtitle files that are for the same piece of media (e.g. same film, or same TV episode, etc.) and compare each subtitle file's text for the same lines of dialogue. The problem is that the start and end times for the same lines will be slightly off by a few hundred milliseconds. For example, taking the line above, in another subtitle file the time for that same line is
00:01:32,320 --> 00:01:34,160
To get both files' versions of the same line of dialogue, you could check to see if there is a line in file two that is within a few hundred milliseconds of file one's start and end times, and that should catch it. Something like that. So I need to manipulate times by adding milliseconds to them and also do comparisons of those times.

Assuming you're on PHP >=5.3 (required for getTimestamp()), this will work:
$unformatted_start = '00:01:32,400';
$unformatted_end = '00:01:34,300';
// Split into hh:mm:ss and milliseconds
$start_array = explode(',', $unformatted_start);
$end_array = explode(',', $unformatted_end);
// Convert hh:mm:ss to DateTime
$start = new DateTime($start_array[0]);
$end = new DateTime($end_array[0]);
// Convert to time in seconds (PHP >=5.3 only)
$start_in_seconds = $start->getTimestamp();
$end_in_seconds = $end->getTimestamp();
// Convert to milliseconds, then add remaining milliseconds
$start_in_milliseconds = ($start_in_seconds * 1000) + $start_array[1];
$end_in_milliseconds = ($end_in_seconds * 1000) + $end_array[1];
// Calculate absolute value of the difference between start and end
$elapsed = abs($start_in_milliseconds - $end_in_milliseconds);
echo $elapsed; // 1900

Did you try strtotime?
if (strtotime($date1) > strtotime($date2)) { # date1 is after date2
# do work here
}
if (strtotime($date1) < strtotime($date2)) { #date2 is after date1
# do other work here
}

Related

Check if name ends by string in PHP

In my folder cache, i have dozens of files whose name is filename-number.json, like
sifriugh-80.json
dlifjbhvzique-76.json
dfhgzeiuy-12.json
...
I have a simple script that cleans my cache dir every 2 hours, deleting files older than 2 hours:
$fileSystemIterator = new FilesystemIterator('cache');
$now = time();
foreach ($fileSystemIterator as $file) {
if ($now - $file->getCTime() >= 3 * 3600) // 2 hours
unlink('cache/' . $file->getFilename());
}
Now, i'm looking to only delete every 2 hours files whose number (before .json but not if number is present at the beginning of the file) does NOT end by -100.json, and those ending by -100.json, every 7 days only.
I know that i can use preg_match() to get names, but is there any effective way to perform it?
There is much simpler way than regex using PHP 8+ str_ends_with() : https://www.php.net/manual/en/function.str-ends-with.php
if (str_ends_with($file->getFilename(), '100.json)) {
// unlink at needed time
} else {
// unlink at needed time
}
For PHP 7, there are several ways to emulate it, check at the bottom of https://www.php.net/manual/en/function.str-ends-with.php
I do not see why you should not use preg_match. It is so good here.
Before using preg_match you should check the first symbol in file name and skip the next code if it is_numeric.
If it is not numeric you need to get only ending "-" can be presented zero or ones + number 1 or more digits + .json ending
(pattern can be something like this /-?\d+\.json$/)
After that you can parse it and know the real number before .json,
Your verification will be something like
If "-" symbol exists and number is 100 check the date for 7 days
If number is not 100 check the date for 2 hours

What Kind of time format is this

I am getting some data from some api and I am getting time in following formats/
PT127M
PT95M
which means 127 minutes and 95 minutes respectively.I want to get 127 from this with default functions.Right now I am using shortcut like below
$duration = "PT127M";
$duration = preg_replace("/[^0-9]/","",$duration);
Some one tell me what kind of format is this and if there is any php function available to retrieve the minutes from it.
You can get minutes like this:
$duration = 'PT127M';
$di = new DateInterval($duration);
$minutes = $di->format('%i');
More info here: http://php.net/manual/en/class.dateinterval.php
It might be related to ISO 8601 Duration date format:
To resolve ambiguity, "P1M" is a one-month duration and "PT1M" is a one-minute duration (note the time designator, T, that precedes the time value). The smallest value used may also have a decimal fraction, as in "P0.5Y" to indicate half a year. This decimal fraction may be specified with either a comma or a full stop, as in "P0,5Y" or "P0.5Y". The standard does not prohibit date and time values in a duration representation from exceeding their "carry over points" except as noted below. Thus, "PT36H" could be used as well as "P1DT12H" for representing the same duration. But keep in mind that "PT36H" is not the same as "P1DT12H" when switching from or to Daylight saving time.
You can use DateInterval to parse in PHP:
Here are some simple examples. Two days is P2D. Two seconds is PT2S. Six years and five minutes is P6YT5M.
With this information you can parse your $duration object with this code:
$duration = 'PT127M';
$duration = new DateInterval($duration); // Create a DateInteval Object
echo $duration->format('%i'); // Print minutes from DateInterval Object

Cannot figure out php date() timestamps for two timestamps

With PHP, I am trying to convert a bunch of numbers into a a readable format, the thing is, I have no idea how/what format these are in or can be parsed in using the date() or time() functions in php. there are two of these as well.
(they're built from a total time spent online and time since last log-on)
onlinetime : 1544946 = 2w 3d 21h 9m
lastonline : 1397087222 = 1h 32m
does anyone know the way to get the two different times from the two different timestamps?
If you have a Unix timestamp, take a look at Convert timestamp to readable date/time PHP. The PHP documentation is here: http://php.net/manual/en/function.date.php.
For the online time, you could do modulo arithmetic to figure out the values for each, and then just make a string out of the result. Someone may have a nicer suggestion for this though.
I think John is right, the first is the number of seconds in the timespan listed. And the second certainly looks like a unix timestamp to me. So here's how you can get what you want from these sets of numbers:
1) For the first number, simply divide the number by the seconds in a given time span and use floor():
$timeElapsed = 154496; // in this case
$weeksElapsed = floor($timeElapsed / 604800);
$remainder = $timeElapsed % 604800;
$daysElapsed = floor($remainder / 86400);
etc...
2) For the second number, you can do the same thing by first getting the current timestamp and then subtracting the given timestamp from it:
$lastOnline = 1397087222; // again, in this case
$currentTimestamp = time();
$elapsedSinceLastLogin = $currentTimestamp - $lastonline;
$weeksSinceLastLogin = floor($elapsedSinceLastLogin / 604800);
etc...

How to convert varied "h m s" Excel time formats?

I have an excel sheet that I am importing but I would like some of the data to be converted down to minutes. Though the formats vary from 5h 5m 6.64s to 6.64s how would i be able to convert this down to only minutes in PHP? (I'm sure DateTime::createFromFormat() wont work as its range is from 0 to 59.)
Also would be converting down to minutes be an easier format to manipulate and graph within a PHP application or converting it to some time object from a PHP class better?
Keep in mind the data has to be formatted, then imported to a MySQL server then read back to a PHP application to graph for statistical purpose. I'm also using cakePHP framework to build the app. Thanks for any feedback.
If all the times have a format like h m s (where any of those are optional), I don't think it would be hard at all to extract the numbers. This could be done with a simple regex like:
/(([0-9]{1,2})h)?(([0-9]{1,2})m)?(([0-9]{1,2}\.[0-9]{0,2})s)?/
And then you can simply put those numbers in PHP's DateTime object. And convert it to a format to store in the database.
If the different parts of the string are always separated by a space, you could simply use:
$timeParts = explode(' ', $timestring); //Separates your time string in parts
//To sum these parts into a total number of minutes:
//First make an array with all multiplication factors to go from part of string to a number of minutes
$factors = array(1/60, 1, 60, 60*24); //Last value is for days, which are probably not necessary.
//Iterate through the $timeParts array
$minutes = 0; //Create $minutes variable, so we can add minutes to it for each string part
while($part = array_pop($timeParts)) { //Process each part of the string, starting from the end (because seconds will always be there even if minutes aren't)
$part = floatval($part); //I guess your numbers will technically be strings, so we need to convert them to floats (because the seconds need to be floats). Also, this function should strip off any letters appended to your numbers.
$factor = array_shift($factors); //Take the first part of the $factors array (because in that array the seconds are first, then minutes and so on)
$minutes += ($part * $factor); //Multiply the string part by its matching factor and add the result to the $minutes variable.
}
I haven't tested this, so you'll need to debug it yourself.

Create text file to read from every day

What I'm attempting to do is create a simple "Quote of the Day" script. What this needs to do is be able to read from a simple .txt file, grab each entry per line and output the contents of that line, once per day. For example, if a .txt file had the following text:
This is the quote of the day
This is another quote of the day
This is the last quote of the day
Then, the script would grab the first block of text, This is the quote of the day and output it on the site. It would then cycle through, line by line, based on each incremental day until the end (and then cycle back to the beginning). Hopefully this would just allow people to cut/paste new info in as it would rely on line numbers, not the content itself.
If anyone even knows of a .XML implementation of this - it would be a big help - trying to figure out the simplest way of going about this. Thanks!
Assuming you had a file with 365 lines (one line per the current day)...
$lines = file("quotes.txt");
$day = date("z");
echo $lines[$day];
You can save the current index line and day on the first line of the file, like this:
01;09-11-2011
This is the quote of the day
This is another quote of the day
This is the last quote of the day
To retrieve the quote you would check if the date is today, if it is you get the nth line otherwise you add 1 to the number, update the date and then get the quote.
This should work with any number of lines in your textfile (untested):
// get lines
$lines = file('lines.txt', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES );
// snap to midnight
$day = mktime(0,0,0, date("n"), date("j"), date("Y")) / (3600*24);
// modulo fun
echo $lines[ $day % count($lines) ];
It's very simple.
1.) You create a text file with 7 lines, each line represents a quote.
2.) PHP: You have to load the file into an array and get the numeric representation of the current day of the week:
$quotes = file('your_file.txt');
$the_quote = $quotes[ date('w') ];
echo $the_quote;
From php.net:
w
Numeric representation of the day of the week
0 (for Sunday) through 6 (for Saturday)
If you want to have a quote for each day in a year, just create a file with 366 lines and use date('z').
The most flexible way is definitely:
$day = date("z");
$file = file('quotes.txt');
$file_length = count($file);
$quote = $file[$day % file_length];
By using the modulus of the day and file length you have a recurring cycle every day from the first line to the last line of the file (and then start again).

Categories