calculate date from seconds in php - php

Calculating future date from seconds.
$var = 5183990; //seconds
$today = '2013-02-16 11:00:00'; //date
like I have 5183990 seconds as a variable $var.
Now I want to know future date/time after 5183990 seconds from current time.

Since time() returns the current timestamp in seconds, just add your interval in seconds to it, then format it as a date:
echo date("Y-m-d H:i:s",time()+$var);

Try this
strtotime('2013-02-16 11:00:00')-time()+$var;
details : http://php.net/manual/en/function.strtotime.php

You can use,
echo date("Y m d h:i:s a",time()+$var);
where,
time() returns the current time then add the seconds in $var it will produce the time after $var seconds....the date() then formats that to your choice...

Related

Subtract 2 minutes from a unix timestamp

Could someone assist me on a timestamp issue.. how can I subtract 2 minutes from this timestamp?
echo 'Settings from database (octopus_import_employees):';
$settings = get_settings('octopus_import_employees');
var_dump($settings);
echo 'Timestamp in human format (Started timestamp):';
$started = date("Y-m-d H:i:s", $settings['started']);
var_dump($started);
var_dump($settings); gets an unix timestamp such as: 342534534
var_dump($started); converts it to a readable format such as: 2019-11-08 05:08:58.
All help would be appreciated.
Timestamps are in seconds so you can subtract 120 seconds (i.e. 2 minutes) from it
$time = $settings['started'] - 120;
echo 'Timestamp in human format (Started timestamp):';
$started = date("Y-m-d H:i:s", $time);
var_dump($started);
#YasinPatel solution is definitely the simplest for your situation. In situations where you don't have a unix timestamp input, one of these methods might be easier to use.
You could create a DateTime object from your timestamp using date_create_from_format and subtract 2 minutes from it, using either sub or modify:
$started = date_create_from_format('U', $settings['started']);
$started->sub(new DateInterval('PT2M'));
echo $started->format('Y-m-d H:i:s');
or
$started = date_create_from_format('U', $settings['started']);
$started->modify('-2 minutes');
echo $started->format('Y-m-d H:i:s');
Demo on 3v4l.org

How do I convert date of format like /Date(1490914800000+0100)/ to mysql datetime format in php?

I have tried to solve it by extracting the numeric part and then parsed it using date function. But it shows me some old date which I guess is not correct.
$datef = "1490914800000+0100";
$adada = date('Y-m-d H:i:s', $datef);
// Gives date 1987-10-13 18:31:28 which is an old date. Please suggest.
One approach, well-covered by this SO question, is to use the DateTime() function to convert time in seconds since epoch to a date, and then display this date using format(). But there are two caveats with your data. First, you appear to have milliseconds since the epoch, which needs to be converted to seconds. Second, you also have a timezone shift, in hours, tagged to the end. I split your $datef string into two parts, epoch and timezone, then arrive at the number of seconds since epoch.
list($epoch, $timezone) = explode('+', $datef);
$epoch = ($epoch / 1000) + (substr($timezone, 0, 2)*60*60) +
(substr($timezone, 2, 2)*60);
$dt = new DateTime("#$epoch");
echo $dt->format('Y-m-d H:i:s');
Output:
2017-03-31 00:00:00
Demo here:
PHP Sandbox
The time seems to be in milliseconds.
You can add the timezone shift to the seconds. 1 hour = 3600 seconds.
$milliSeconds = intval("1490914800000");
$seconds = $milliSeconds/1000;
$date = date("Y-m-d H:i:s", $seconds);

How to get seconds elapsed since midnight

Using PHP how do you get the number of seconds elapsed since midnight of the current day?
All i've tried right now is:
$hour=substr(date("h:i:s"),0,2);
$minute=substr(date("h:i:s"),3,2);
echo $hour."\r\n";
echo $minute."\r\n";
...but it doesn't return the correct server time of the response and I don't know how to do that.
This should work.
echo time() - strtotime("today");
This will only show your servers timezone though.
Simplest I believe would be dividing the current time (in seconds) by the number of seconds in a day (60*60*24) and taking the remainder:
(time() % 86400)
If you are using DateTime:
$timeDiff = $time->diff(new \DateTime("today"));
$timeDiffSec = $timeDiff->h* 3600 + $timeDiff->i*60 + $timeDiff->s;
echo (date('G') * 3600 + date('i') * 60);
Multiply the current hour by the number of seconds in each hour and add it to the number of minutes multiplied by the number of seconds in each minute.
I think you want to get time from start of the day to current hours and seconds of the day, this can be done like this, you will still need to set your timezone time in place of 'Asia/Karachi'. This gets correct time since midnight in user's timezone instead of server's timezone time.
Here is working link:
http://codepad.viper-7.com/ykJC2R
//Get current time timestamp
$time_now = time();
//Create DateTime class object
$date = new DateTime();
//Set timestamp to DateTime object
$date->setTimestamp( $time_now );
//Set timezone so that code don't get server's timezone midnight time
$date->setTimezone(new DateTimeZone('Asia/Karachi'));
//Print current time in user's timezone
echo $date->format('Y-m-d H:i') . "<br />";
//Get time stamp for midnight tonight
$date->modify('today midnight');
$midnight_time = $date->getTimestamp();
//Print midnight time in user's timezone
echo $date->format('Y-m-d H:i') . "<br />";
//Now you will need to subtract midnight time from current time in user's timezone
$seconds_since_midnight = $time_now - $midnight_time;
//Print seconds since midnight in your timezone
echo $seconds_since_midnight;
The shortest solution would probably be this:
$time = "12:34:56";
echo strtotime("{$time}UTC", 0);
The reason this works is that strtotime uses the second parameter to determine the date part of the time string. In this case, I'm using 0, which means the full string results in 1970-01-01 12:34:56 UTC. strtotime then returns the UNIX timestamp (the number of seconds elapsed since 1970-01-01 00:00:00 UTC). Note: the first parameter has UTC appended to prevent the time being interpreted as local.
DateTime (with microseconds)
A faster (3×) and more precise alternative to the already mentioned DateTime::diff solution:
$date = new DateTime;
[$h, $m, $s] = explode(':', $date->format('H:i:s.u'));
echo $h * 3600 + $m * 60 + $s;
Based on your comment, if you are receiving the time as a string and want to calculate the number of seconds from that time:
$time = strtotime($_GET['time']); // Do some verification before this step
$midnight = strtotime("00:00"); // Midnight measured in seconds since Unix Epoch
$sinceMidnight = $time - $midnight; // Seconds since midnight
There you go. Read into time() function of PHP and strtotime().
In Carbon, the number of seconds elapsed since midnight can be found like this:
$seconds_since_midnight = $dt->secondsSinceMidnight();
And though there's no minutes since midnight I suppose you do:
$minutes_since_midnight = (int) floor($dt->secondsSinceMidnight()/60);
echo time() - strtotime('today');
I'm keeping the rule that operations on numbers are always faster than operations on strings. When the numbers are integers, operations are even faster (because CPU registers are always "integer wide", means have 32-bit or 64-bit and all other non-floating point types are converted to integer before any operation is performed).
Anyway, I found such solution to count seconds till midnight with timezone include:
$tillmidnight = 86400 - (time() - mktime(0, 0, 0));
You wanted to get seconds elapsed since midnight so:
$sincemidnight = time() - mktime(0, 0, 0);
It is good to review your php.ini also and set your time zone (date.timezone under [Date] section) there. If you do not have access to php.ini, you can set your time zone in PHP code using date_default_timezone_set(); function.

What is the proper way of converting a timestamp to a human readable date?

i've got 2 time stamps: $start_time = 1312346227; and $end_time = 1312346466;
and i am trying to substract them to see the time inbetween $end_time = $end_time - $start_time;
and i get 239.
What is the proper way of converting this to a human readable date?
if i try echo date("h:i:s A",$end_time); i get 04:03:59 and it should be 00:03:59
any ideas?
Thanks
If you have PHP 5.3, use the DateInterval class.
Example stolen from the manual page on DateInterval::format():
<?php
$january = new DateTime('2010-01-01');
$february = new DateTime('2010-02-01');
$interval = $february->diff($january);
// %a will output the total number of days.
echo $interval->format('%a total days')."\n";
// While %d will only output the number of days not already covered by the
// month.
echo $interval->format('%m month, %d days');
?>
You get addiionl four hours, because of your timezone. Remember that unix timestamp is the number of seconds since 1970-01-01 00:00:00 UTC. If you (or your server) are in UTC+4 TZ, then date() will implicitly do a timezone conversion to your local time.
Solution? Use gmdate() instead
You need to set your timezone correctly. http://www.php.net/manual/en/function.date-default-timezone-set.php

How to get duration in terms of minutes by subtracting a previous time stamp from the present time in PHP?

How to get duration in terms of minutes by subtracting a previous time stamp from the present time in PHP?
The format of time stamp is like
2009-12-05 10:35:28
I want to calculate how many minutes have passed.
How to do it?
To do this in MySQL use the TIMESTAMPDIFF function:
SELECT TIMESTAMPDIFF(MINUTE, date_lastaccess, NOW()) FROM session;
Where session is the table and date_lastaccess is a DATE / DATETIME field.
If you don't wanna add a library, you can do this pretty easily:
<?php
$date1 = "2009-12-05 10:35:28";
$date2 = "2009-12-07 11:58:12";
$diff = strtotime($date2) - strtotime($date1);
$minutes_passed = $diff/60;
echo $minutes_passed." minutes have passed between ".$date1." and ".$date2;
?>
Check out some pretty date libraries in PHP. Might have something for you. Here's one : http://www.zachleat.com/web/2008/02/10/php-pretty-date/
strtotime("now") - strtotime("2009-12-05 10:35:28")
That will get you seconds difference. Divide by 60 for minutes elapsed. If you have any information on the time zone of the initial timestamp, however, you'd need to adjust the "now" to a more comparable time
something like that
$second = strtotime('now') - strtotime($your_date);
$minute = $second / 60;
strtotime return the number of seconds since January 1 1970 00:00:00 UTC, so you can easily manipulate this. if you need don't want to have 35.5 minute you can use floor to round up the number. Last remark both time need to be in the same timezone or you are going to count the timezone difference also.
You could just use
$timestamp = time();
$diff = time() - $timestamp
$minutes = date( i, $diff );
function timeAgoMin($timestamp){
if(!is_int($timestamp)){
$timestamp = strtotime($timestamp);
}
return ((time() - $timestamp) / 60);
}

Categories