PHP calculate date interval from 0/0/0 00:00:00 [closed] - php

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
I need to calculate a duration and make it human readable.
e.g. I have a string: "2 days 4 hours". I need my code to calculate the duration of that string as a timestamp and to make it human readable.
My problem is that if I add the timestamp to 0, it starts from 1/1/1970, but I need it to just calculate the duration.
I tried to subtract 1/1/1970 01:01:00 to 0 but when calculating it returns a no-sense result.

If I understand you correctly, you would like to transform something like:
$dateString = "2 days 4 hours";
to timestamp?
If that is the case, and you know there will always be days/hours you could do something like:
$dateString = "2 days 4 hours";
preg_match_all('!\d+!', $dateString , $numbersOnly);
$partialTimeStamp= (($numbersOnly[0][0]*24)+$numbersOnly[0][1])*3600;
print_r($partialTimeStamp); // will print 187200
With this you will have a numbers of seconds. If for example you also have minutes in your string you would do:
$dateString = "2 days 4 hours 15 minutes";
preg_match_all('!\d+!', $dateString , $numbersOnly);
$partialTimeStamp= (($numbersOnly[0][0]*24)+$numbersOnly[0][1])*3600 + $numbersOnly[0][2]*60;
print_r($partialTimeStamp); // will print 188100
And with this partial timestamp, you can than calculate next timestamp like:
$nextTimeStamp = time () + $partialTimeStamp;
print_r($nextTimeStamp);
EDIT: Missed the "back to human readable" part..
For this, you would do something like:
$days = floor($partialTimeStamp/ 86400);
$partialTimeStamp = $partialTimeStamp - $days*86400;
$hours = floor($partialTimeStamp/ 3600);
$min = floor($partialTimeStamp/ 60 % 60);
And than just this:
print_r($days." days ".$hours." hours ".$min. " minutes");// will output 2 days 4 hours 15 minutes
I hope this helps.
BR

Related

Why does print strtotime('2020-11-02') - strtotime('2020-11-01'); return 90,000 seconds? [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
print strtotime('2020-01-02') - strtotime('2020-01-01'); returns 86,400
print strtotime('2020-02-02') - strtotime('2020-02-01'); returns 86,400
etc.
print strtotime('2020-11-02') - strtotime('2020-11-01'); return 90,000 seconds
My apologies if this has been asked before. I checked and didn't find anything.
My program is calculating the days between two dates, counting the first date as one.
Here is a sample I'm working with:
<?php
function dateDifference($d1, $d2)
{
// calulating the difference in days
// get seconds between dates
$diff = strtotime($d2) - strtotime($d1);
// 1 day = 24 hours
// 24 * 60 * 60 = 86400 seconds
// '2020-11-02' and '2020-11-01' returns three days.
return ceil(abs($diff / 86400))+1;// Start day is day one.
}
$d1 = '2020-11-01';
$d2 = '2020-11-02';
$trip_days = dateDifference($d1,$d2);
// returns three days, not two.
echo 'Total Days between 11/01/2020 and 11/02/2020: ' . $trip_days . "\n";
$d1 = '2020-10-01';
$d2 = '2020-10-02';
$trip_days = dateDifference($d1,$d2);
echo 'Total Days between 10/01/2020 and 10/02/2020: ' . $trip_days . "\n";
?>
This year, daylight saving's ended on Sunday November 1st.
We got an extra hour which is 3,600 seconds,
86,400 + 3,600 = 90,000
This seems like a daylight savings time issue.
Some places, like Canada and some US states, changed from daylight savings time to standard/winter time on Sunday 1st of November 2020, making the clock jump from 02:00 back to 01:00. Therefore, you got an extra hour that night.
Source: https://www.timeanddate.com/time/dst/events.html

php DateTime() returning current date when assigning date in past [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
I need to display the duration between the reported date / time and the time date / now. eg. 1 days 15 hours 48 mins
$reported = the_sub_field('reported'); //format eg. 27 January, 2020 12:00
$currdt= new DateTime(Date("Y-m-d H:i"));
var_dump($currdt);
$reporteddt= new DateTime($reported );
var_dump($reporteddt);
$interval = $currdt->diff($reporteddt);
var_dump($interval);
$duration = $interval->d ." days ".$interval->h ." hours ". $interval->i ." mins";
Many thanks
You have to remove the comma.
$reported = '28 January, 2020 12:00';
$reported = str_replace(',', '', $reported);
$reporteddt= new DateTime($reported);
var_dump($reporteddt);
Test

strtotime and weird results when calculating time differences (datetime)

I've been trying at this for a bit and can't get the damn code to work.. This is my first post, I've gone through a few, tried a million different ways.. I just want to get the difference in hours, then I'm set, I'll get the rest figured out..
Right now, it's giving me unusual answers (say there's a 2 hour difference, it'll give me 14 as an answer) Pardon my coding, I haven't done this in years and have no real formal training. I'll be as thorough as possible in my comments, and thanks a LOT. Any links appreciated. I have tried a LOT. Using PHP 5.3.something, and am pulling off a Wordpress 3.7.1 database.
Thanks in advance for the help for a beginner. I want to display "Updated x hours ago". Once I have the darned thing displaying the correct result, I'll figure the rest out.
//This is the current date, putting it into strtotime so everything is in the same format. It displays accurately.
$currentDate = date("Y-m-d");
$currentTime = date("H:i:s");
$currentDateHour = date("H", strtotime($currentDate . $currentTime));
// This is the date I'm pulling from the database, it only displays
// when in strtotime for some reason. It displays accurately to what is in the mySQL DB
$upDate = date("Y-m-d H", strtotime($row2[post_date]));
// Some variables to make life easier for later if statements if I ever get that far. Displays accurately.
$upDatehour = date("H", strtotime($row2[post_date]));
// trying simple subtraction
$hour = $currentDateHour - upDatehour;
// this is where the result is incorrect, what is wrong here? Any method I've tried gives me the same result, with or without strotime.. it's gotta be something simple, always is!
print strtotime($hour);
You can drastically simplify your code. I'd recommend refactoring it to use DateTime and specifically DateTime::diff().
$now = new DateTime();
$post = new DateTime($row2['post_date']);
$interval = $now->diff($post);
echo "Updated " . $interval->h . " hours ago";
Working example: http://3v4l.org/23AL6
Note that this will only show up to 24 hours difference. If you want to show all hours even for a difference of more than 24 hours, you'll need to figure in the days. Something like this:
$hours = $interval->h + ($interval->format("%a") * 24);
echo "Updated $hours hours ago";
Working example: http://3v4l.org/ilItU
If you are just trying to get the number of hours between two arbitrary times, the easiest way would be to get the difference in seconds of the two times, and then divide by 3600 to determine the number of hours between the two dates.
Here is a basic example:
<?php
$row2['post_date'] = '2013-12-02 07:45:38'; // date from database
$now = time(); // get current timestamp in seconds
$upDate = strtotime($row2['post_date']); // convert date string to timestamp
$diff = $now - $upDate; // subtract difference between the two times
$hours = floor($diff / 3600); // get the number of hours passed between the 2 times
echo $hours; // display result
Also, Wordpress has a built in function that may end up doing what your ultimate goal is, see wordpress function human_time_diff().
Example:
<?php echo human_time_diff( get_the_time('U'), current_time('timestamp') ) . ' ago';
Result:
2 days ago.
Example how to get difference between dates in hours:
$diff = date_diff(date_create(), date_create($row2['post_date']));
$hours = $diff->days * 24 + $diff->h;
If you wish to format output number with leading zeros, you can use sprintf() or str_pad() function. Example of sprintf() use for HH:mm format:
echo sprintf('%02d:%02d', $hours, $diff->i);
demo

Time Format -> 635151121709530000? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
Can anybody tell me what time format is this 635151121709530000 and how to convert, the result is something like 2013-9-18 14:42:50
Thanks
There's not enough info here to convert your number to a time. There are at least two common ways to represent a point in time:
The first (and most common) is that the number represents a count of units of time between the time represented by the timestamp and some "epoch" date. In order to convert it to a date, you'd need two pieces of info: the scale (the amount of time that elapses between the timestamps N and N+1), and a reference timestamp (commonly the epoch date, which is the date/time that the number 0 represents).
Without that info, you would need at least two timestamps, and the date/time each represents. You could then find the difference between them, divide by the number of seconds, and that'll give you the scale. You could then extrapolate to find the epoch date.
The second possibility is that the number is a bit field, where each part of the date is represented by a certain set of bits in the integer.
If that's the case, then you're somewhat screwed; there could be all kinds of math going on to fit the date parts into a bit field. You will have to either ask someone in charge of the system, or if that's you now, examine the code that generates timestamps.
Edit: If we take the numbers you provided in the comments:
635155956336800000 2013-9-24 05:00:33
635155957368670000 2013-9-24 05:02:16
635155968617830000 2013-9-24 05:21:10
635155968728200000 2013-9-24 05:21:12
635155971811300000 2013-9-24 05:26:21
635155972798800000 2013-9-24 05:27:59
635155978347870000 2013-9-24 05:37:14
Let's see if the numbers make sense as counts.
Take the first and last times and find the difference between their respective timestamps.
635155978347870000 - 635155956336800000 = 22011070000 ticks
Divide by the number of seconds separating the two times ((37*60+14) - 33 == 2201 seconds)
22011070000 ticks / 2201 sec = 10000486.142662 ticks/sec
Round to a nice even number, cause timestamps are based on useful intervals unless you're obfuscating. So in your case, it looks like the scale is 10 million ticks per second, or 100ns per tick.
Verify with the other timestamps (in this case, the 5:27:59 one and the 5:00:33):
635155972798800000 - 635155956336800000 == 16462000000 ticks
16462000000 ticks / 10000000 ticks/sec = 1646.2 sec
(27*60+59) - 33 == 1646 sec
So 100ns looks about right. In order to be sure, though, we'd need timestamps further apart. Just to make sure this is indeed a count rather than, say, two 31-bit numbers representing the year and the current second of that year.
Assuming this is a count, if we take the first timestamp and divide by 10 million:
635155956336800000 ticks / 10000000 ticks/sec = 63515595633.6800000 sec
That's 63.5 billion seconds since the epoch. For reference, 32-bit signed timestamps (which number a bit over 2 billion) will run out in 2038, 68 years from the Unix epoch (1970). This number is about ~29.58 times that, or 29.58 * 68 ~= 2011 years.
That'd put the epoch around the beginning of the first century CE. 1 CE is a significant enough date that it'd make sense as the epoch date. I don't feel like doing the math to confirm that, though.
Corresponding with cHao's 10000000 ticks per second, but using a base date of 01/01/0001 as I'd originally suggested:
$values = array(
array(635155956336800000, "2013-9-24 05:00:33"),
array(635155957368670000, "2013-9-24 05:02:16"),
array(635155968617830000, "2013-9-24 05:21:10"),
array(635155968728200000, "2013-9-24 05:21:12"),
array(635155971811300000, "2013-9-24 05:26:21"),
array(635155972798800000, "2013-9-24 05:27:59"),
array(635155978347870000, "2013-9-24 05:37:14"),
);
function convert($date) {
static $monthArray = array(
31,29,31,30,31,30,31,31,30,31,30,31
);
$date = $date / 10000000 / 24 / 60 / 60;
$y = floor($date / 365.2425);
$YYYY = $y + 1;
$z = 365 * $y + floor($y/4) - floor($y/100) + floor($y/400);
$d = $date - $z;
$month = 1;
while (true) {
$d -= $monthArray[$month - 1];
if ($d < 0) break;
$month++;
$dd = $d;
}
$hh = ($dd - floor($dd)) * 24;
$hours = floor($hh);
$mm = ($hh - floor($hh)) * 60;
$minutes = floor($mm);
$ss = ($mm - floor($mm)) * 60;
$seconds = floor($ss);
return sprintf('%04d-%02d-%02d %02d:%02d:%02d', $YYYY, $month, floor($dd), $hours, $minutes, $seconds);
}
foreach($values as $value) {
echo convert($value[0]), PHP_EOL;
}
gives:
2013-09-22 05:00:33
2013-09-22 05:02:16
2013-09-22 05:21:01
2013-09-22 05:21:12
2013-09-22 05:26:21
2013-09-22 05:27:59
2013-09-22 05:37:14
I'm not sure where the 2-day discrepancy comes from, but the output can probably arbitrarily have 2 days added and unless you're playing with extremely historic dates closer to the 0 timestamp mark, then it'd probably be a good enough function to use

Calculate age from given datetime stamp - PHP [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I have a variable $dob which returns a date, in the following format: 1970-02-01 00:00:00
How can I use php to calculate the age of the person?
Your question is explained in detail in the PHP documentation, it bascially goes like this:
// create a datetime object for a given birthday
$birthday = new DateTime("2012-12-12");
// substract your timestamp from it
$diff = $birthday->diff($dob);
// output the difference in years
echo $diff->format('%Y');
Try this:
<?php
$age = '1970-02-01 00:00:00';
echo (int)((time()-strtotime($age))/31536000);
Output: 43, in years.
$dob = '1970-02-01 00:00:00';
$date = new DateTime($dob);
$diff = $date->diff(new DateTime);
echo $diff->format('%R%a days');
Basically stolen from here: http://uk1.php.net/manual/en/datetime.diff.php
Formatting options: http://uk1.php.net/manual/en/dateinterval.format.php
One-liner:
echo date_create('1970-02-01')->diff(date_create('today'))->y;
Demo.
i would try this
$user_dob = explode('-',$dob);
$current_year= date('Y');
$presons_age = $current_year - $user_dob[0];
This is an untested code but i feel u should get the logic.
strtotime() will convert your date into a timestamp, then subject that from time() and the result is the age in seconds.
$age_in_seconds = time() - strtotime('1970-02-01');
To display the age in years (+- 1 day), then divide by the number of seconds in a year:
echo "Age in whole years is " . floor($age_in_seconds / 60 / 60 / 24 / 365.25);

Categories