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.
Related
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
I've tried various things, I want to find out how to specifically do it for now, 7 days ago and 1 month ago.
I tried
$timestamp = round(microtime(true)*1000);
I got a random number and then E+12 on the end what's that? When I tried to put '$timestamp' into a json string to POST to a url to get an array with results within the time periods (which have to be declared in unix timestamps in milliseconds), I get no result back. If I use a unix timestamp converter only and put it into the json string, it works. How I can do this so it's dynamic based on the time in PHP? Thanks
E12 means "multiplied by 10 to the 12th power" otherwise known as scientific notation. if you want to just output the digits, you can do something like this
$timestamp = round(microtime(true)*1000);
echo number_format($timestamp,0,".","");
That will output just the number without scientific notation.
To get timestamps for various days you can use strtotime().
$microSeconds = microtime(true) - (float)time();
$sevenDaysAgo = (float)strtotime('-7 days') + $microSeconds;
$oneMonthAgo = (float)strtotime('-1 Month') + $microSeconds;
$sevenDaysAgo *= 1000;
$oneMonthAgo *= 1000;
echo number_format($sevenDaysAgo,0,".","");
echo number_format($oneMonthAgo,0,".","");
I have tried exploding the times, to work with parts before and after the ":" with minimal success. I am receiving both times via XML feed, so I can convert my received strings as necessary, or multiply them by another figure to work with as I need.
$time_1 = "00:59.8408";
$time_2 = "01:00.4734";
$difference = $time_2 - $time_1;
or another way of calculating the difference, should give me back
0.6326
I will be happy to accept any advice. I have attempted subtracting strtotime converted variables, I have as I mentioned above exploded the string with unfavorable results. The, what I believe is, milliseconds have also been an obstacle that I have not worked with in the past.
I appreciate you reading this.
The minus operator in PHP only works with numbers. Your strings will be converted to numbers which then is 1 - 0, so the difference is 1:
$time_1 = "00:59.8408";
$time_2 = "01:00.4734";
$difference = $time_2 - $time_1;
var_dump($difference); # int(1)
Instead write a function that converts the string into seconds as a float like in this example:
/**
* convert time string to seconds
*
* #param string $time %i:%s.%u
* #return float
*/
function time_to_seconds($time) {
sscanf($time, '%d:%f', $minutes, $seconds);
return $minutes * 60 + $seconds;
}
This is pretty straight forward: scan the string first for digits, then the colon and then a float. As the first digits are the minutes, multiply those with 60 and add the seconds as float (one minute is 60 seconds). Return the result (no error checking in there, see sscanf to turn this into production code.
Then do the operation with the results:
$difference_in_seconds = time_to_seconds($time_2) - time_to_seconds($time_1);
var_dump($difference_in_seconds); # double(0.6326)
And that's it. The most important part is that you need to know how to treat the data that is encoded in your string(s) here. Parse the string according to that.
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...
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
}