getting only time timestamp from string - php

Suppose I have a time string '9:30' which I want to convert to timestamp.
What I do right now is extracting it and manually calculate the timestamp.
list($hour, $minute) = explode(':', '9:30');
$timestamp = $hour * 3600 + $minute * 60;
I'm wondering whether there is a smart way using Carbon or DateTime object.

use strtotime()
manual
$time = '9:30';
$timestamp = strtotime($time);
echo date('H:i',$timestamp);

I don't think you'll be able to get a timestamp from only hour or minute, as timestamp is number of seconds from 00:00:00 Thursday 1 January 1970 (check wikipedia link for more details). So without the date part you can't have a timestamp. Could you please explain how you're planning to use this?
If you're planning to calculate a different timestamp from a given datetime, then you can just do it differently. Say you're planning to get the timestamp 1 day or 24 hours after given time, then you can do it like this (non object oriented way):
$givenTimestamp = strtotime('17-06-2018 09:30:00');
$dayInSeconds = 24*60*60;
$calculatedTimeStamp = $givenTimestamp + $dayInSeconds;
If you're just trying to get how many seconds has been passed for the time section of the timestamp (like 9:30 in your example for a given day), then you can just do it like this:
list($hour, $minute) = explode(':', date ('H:i', strtotime('2018-06-16 09:30:00')));
$secondsSinceStartOfDay = intval($hour)*60*60 + intval($minute) * 60;
You may get the same result without using the intval on $hour and $minute, but it would be better to use intval on them to avoid possible issues in some cases.
Update with Carbon
From Carbon documentation, it seems like you still need the date part to generate the timestamp. So if you have your $date like this '2018-06-16' and $time like this '09:30', then you can recreate your datetime like this:
$dateTimeString = $date .' '. $time .':00';
$carbonDateTime = Carbon::parse($dateTimeString);
// $carbonDateTime will now have your date time reference
// you can now get the timestamp like this
echo $carbonDateTime->timestamp;

Related

Figuring out the difference in days between events

I have a MySQL DB with StartDates in the format of yyyy-mm-dd and starttimes in the format of HH:MM using a 24 hour clock. What would be the easiest way to compare the difference of two days in PHP? Would using a datetime object could I set it to be with the information given and just give it to zeros for the seconds? I need to get the amount of time between both dates down to the minute. I was putting the startdate (Just the day since its always within the same month for my application) and time together concatenated together and then pulling out what I need like below, but I haven't been able to get it straight yet. Thanks for the look!
$tempvar1 = $times[$i][$j];
$tempvar2 = $times[$i][$j+1];
$day1 = $tempvar1[0].$tempvar1[1];
$day2 = $tempvar2[0].$tempvar2[1];
$hours1 = $tempvar1[2].$tempvar1[3];
$hours2 = $tempvar2[2].$tempvar2[3];
$minutes1 = $tempvar1[5].$tempvar1[6];
$minutes2 = $tempvar2[5].$tempvar2[6];
$numdays = ($day2-$day1) - 1;
$time1 = ($hours1*60)+$minutes1;
$time2 = ($hours2*60)+$minutes2;
MySQL has plenty of date/time functions:
SELECT TIMEDIFF(endtime, starttime), DATEDIFF(endtime, starttime)
FROM ...
doc links for timediff and datediff
That'll you get strings in the format of 'hh:mm:ss.ssss' for timediff, and a straight-up integer representing the days between the two dates, respectively.

Check interval between datetimes in PHP

I have a field in database that has type of datetime in which I add time when user visit a page. When user again comes I want to check the interval between his first visit and current. If it is less or equal to 1 hour then I want to show him some message.
I store time like this
2011-03-04 00:25:01
The thing that I want to ask that how to check the interval in PHP
You could try
SELECT COUNT(#UserID) FROM table WHERE LastVisit > (DateADD(now(),interval -1 Hour))
you can then check the count
Edit: added FROM clause
If you have PHP >= 5.3 you can use DateTime objects and functions:
$visit = DateTime::createFromFormat('Y-m-d H:i:s', '2011-03-04 00:25:01');
$now = new DateTime("now");
$diff = $now->diff($visit);
What you can so is, retrieve the the datetime, store it in a variable.
Create a var with time().
You can then convert the db datetime to a timestring using strtotime()
Subtract the datetime timestring from the new time. That should give you a difference in seconds. You can then manipulate your values and do the relevant checks.
$db = datetime_from_database;
$now = time();
$last = strtotime($db);
$diff = $now - $last; //this is in seconds
You can do something like
$minutes = $diff / 60;
If ($minutes > 60) echo 'more than 1 hour; 60 minutes';
Just work in it.
You can then use the date functions to format the new datetime using the $now and update the database.

How to obtain, increment, and compare datetime in PHP?

I am developing a quiz site and there is time for x min to answer the quiz. So when user clicks on start quiz link the starttime (current time at this instant) is recored in session. Also the endtime (start_time+ 30 min) is recorded in session and every time he submits a answer the current time is compared with the quiz end time. Only if the current time is less than end_time the answer should be accepted.
How can I get the currentdatetime?
How can I add x minutes to current this datetime?
How can I compare (<=) datetime ?
I think we should use date time. Is it right?
PHP measures time as seconds since Unix epoch (1st January 1970). This makes it really easy to work with, since everything just a single number.
To get the current time, use: time()
For basic maths like adding 30 minutes, just convert your interval into seconds and add:
time() + 30 * 60 // (30 * 60 ==> 30 minutes)
And since they're just numbers, just do regular old integer comparison:
$oldTime = $_SESSION['startTime'];
$now = time();
if ($now < $oldTime + 30 * 60) {
//expired
}
If you need to do more complicated things like finding the date of "next tuesday" or something, look at strtotime(), but you shouldn't need it in this case.
use php builtin functions to get time:
<?php
$currentTimeStamp = time(); // number of seconds since 1970, returns Integer value
$dateStringForASpecificSecond = date('Y-m-d H:i:s', $currentTimeStamp);
?>
for your application that needs to compare those times, using the timestamp is more appropriate.
<?php
$start = time();
$end = $start + (30 * 60); // 30 minutes
$_SESSION['end_time'] = $end;
?>
in the page where the quiz is submitted:
<?php
$now = time();
if ( $now <= $_SESSION['end_time'] ) {
// ok!
}
?>
Use the time() function to get a UNIX timestamp, which is really just a large integer.
The number returned by time() is the number of seconds since some date (like January 1, 1970), so to add $x minutes to it you do something like (time() + ($x*60)).
Since UNIX timestamps are just numbers, you can compare them with the usual comparison operators for numbers (< <= > >= ==)
time() will give you the current time in seconds since 1/1/1970 (an integer), which looks like it should be good.
To add x minutes, you'd just need to add x*60 to that, and you can compare it like any other two integers.
Source: http://us3.php.net/time
This is an old question but I wanted to provide an answer based on the PHP 5.2 DateTime class which I feel is much easier to use and much more versatile than any previous functions.
So how can i get the currentdatetime?
You can create a new DateTime object like this:
$currentTime = new DateTime();
But at this point, $currentTime is a datetime object and must be converted to a string in order to store it in a database or output it.
$currentTime = $currentTime->format('Y-m-d H:i:s');
echo $currentTime;
Outputs 2014-05-10 21:14:06
How can i add x minutes tocurrent this datetime?
You can add x minutes with the modify method:
$currentTime = new DateTime();
$addedMinutes = $currentTime->modify('+10 minutes');
echo $addedMinutes;
Outputs 2014-05-10 21:24:06
How can i comapare (<=) datetime ?
With the DateTime class, you can not only easily compare datetime objects, you can get the difference between them.
$currentTime = new DateTime('2014-05-10 21:14:06');
$addDays = $currentTime->modify('+10 days');
To compare
if ($currentTime >= $addDays) {
//do something//
}
$diffTime = new DateTime('2014-05-10 21:14:06');
$diff = $addDays->diff($diffTime);
$diff = $diff->format('There are %d days difference.');
echo $diff;
Outputs There are 10 days difference.

Determining elapsed time

I have two times in PHP and I would like to determine the elapsed hours and minutes. For instance:
8:30 to 10:00 would be 1:30
A solution might be to use strtotime to convert your dates/times to timestamps :
$first_str = '8:30';
$first_ts = strtotime($first_str);
$second_str = '10:00';
$second_ts = strtotime($second_str);
And, then, do the difference :
$difference_seconds = abs($second_ts - $first_ts);
And get the result in minutes or hours :
$difference_minutes = $difference_seconds / 60;
$difference_hours = $difference_minutes / 60;
var_dump($difference_minutes, $difference_hours);
You'll get :
int 90
float 1.5
What you now have to find out is how to display that ;-)
(edit after thinking a bit more)
A possibility to display the difference might be using the date function ; something like this should do :
date_default_timezone_set('UTC');
$date = date('H:i', $difference_seconds);
var_dump($date);
And I'm getting :
string '01:30' (length=5)
Note that, on my system, I had to use date_default_timezone_set to set the timezone to UTC -- else, I was getting "02:30", instead of "01:30" -- probably because I'm in France, and FR is the locale of my system...
You can use the answer to this question to convert your times to integer values, then do the subtraction. From there you'll want to convert that result to units-hours-minutes, but that shouldn't be too hard.
Use php timestamp for the job :
echo date("H:i:s", ($end_timestamp - $start_timestamp));
$d1=date_create()->setTime(8, 30);
$d2=date_create()->setTime(10, 00);
echo $d1->diff($d2)->format("%H:%i:%s");
The above uses the new(ish) DateTime and DateInterval classes. The major advantages of these classes are that dates outside the Unix epoch are no longer a problem and daylight savings time, leap years and various other time oddities are handled.
$time1='08:30';
$time2='10:00';
list($h1,$m1) = explode(':', $time1);
list($h2,$m2) = explode(':', $time2);
$time_diff = abs(($h1*60+$m1)-($h2*60+$m2));
$time_diff = floor($time_diff/60).':'.floor($time_diff%60);
echo $time_diff;

Adding time in PHP

I am pulling a datetime from a mysql db and i would like to add X hours to it then compare it to the current time. So far i got
$dateNow = strtotime(date('Y-m-d H:i:s'));
$dbTime = strtotime($row[0]);
then i tried $dbTime + strtotime("4 hours"); but 4 hours seem to add 4hrs to the current time instead of raw 4hours. How do i add X hours to dbTime?
NOTE: I am using php 5.1.2 so date_add doesnt work (5.3.0)
You have quite a few options here:
1.
$result = mysql_query("SELECT myDate FROM table");
$myDate = mysql_result($result, 0);
$fourHoursAhead = strtotime("+4 hours", strtotime($myDate));
2.
// same first two lines from above
$fourHoursAhead = strtotime($myDate) + 4 * 60 * 60;
3.
$result = mysql_query("SELECT UNIX_TIMESTAMP(myDate) FROM table");
$myDate = mysql_result($result, 0);
$fourHoursAhead = $myDate + 4 * 60 * 60;
4.
$fourHoursAhead = strtotime("+4 hours", $myDate);
5.
$result = mysql_query("SELECT UNIX_TIMESTAMP(DATE_ADD(myDate, INTERVAL 4 HOUR))");
$fourHoursAhead = mysql_result($result, 0);
then i tried $dbTime + strtotime("4 hours"); but 4 hours seem to add 4hrs to the current time instead of raw 4hours. How do i add X hours to dbTime?
strtotime has an optional second argument. Provide a Unix timestamp there and the output will be relative to that date instead of the current date.
$newTime = strtotime('+4 hours', $dbTime);
You can also use the fact that Unix timestamps are seconds-based - if you know what four hours are in seconds, you can just add that to the time integer value.
time() and strtotime() result in unix timestamps in seconds, so you can do something like the following, provided your db and do your comparison:
$fourHours = 60 * 60 * 4;
$futureTime = time() + $fourHours;
strtotime("+4 hours", $dbTime);
The second argument is the timestamp which is used as a base for the calculation of relative dates; it defaults to the current time. Check out the documentation.
Edit:
For short periods of time, max 1 week, adding seconds to a timestamp is perfectly acceptable. There is always (7 * 24 * 3600) seconds in a week; the same cannot be said for a month or year. Furthermore, a unix timestamp is just the number of seconds that have elapsed since the Unix Epoch (January 1 1970 00:00:00 GMT). That is not effected by timezones or daylight-savings. Timezones and daylight-savings are only important when converting a unix timestamp to an actual calendar day and time.
I tend to use the time() function, and this page from the manual shows them displaying the date a week in the future:
http://us3.php.net/manual/en/function.time.php
Here's how I'd do it:
Pull the time from the database using the UNIX_TIMESTAMP() function.
The UNIX timestamp is in seconds, so add 4*60*60 to it.
Convert the modified UNIX timestamp to a date using PHP's localtime() or strftime() function.
query("SELECT UNIX_TIMESTAMP(someDatetimeColumn) ...");
. . .
$dbTimeAdjusted = localtime($row[0] + 4*60*60);
Probably the safest way to do the compare is right in the SQL
SELECT * FROM my_table WHERE someDateTimeColumn < DATE_ADD(NOW(), INTERVAL 4 hour)
And since you're assembling it in PHP, you can dynamically replace the "4 hour" bit with whatever your code needs to compare.
(Note: putting the entire calculation on the other side of the comparison to the column allows MySQL to do the calculation once per query, rather than once per row, and also use the table's index, if that column has one.)
Assuming that the timestamp returned by the DB is in SQL format, the following should work fine:
$dbTime = strtotime($row[0]);
$nowTime = time();
$future_dbTime = strtotime("+4 hours", $dbTime);
$diff_time_seconds = $nowTime - $dbTime;
if ($diff_time_seconds > 0) {
echo "The current time is greater than the database time by:\n";
$not_equal = true;
}
if ($diff_time_seconds == 0) {
echo "The current time is equal to the database time!";
}
if ($diff_time_seconds < 0) {
echo "The current time is less than the database time by:\n";
$not_equal = true;
}
if ($not_equal) {
$diff_time_abs_seconds = abs($diff_time_seconds);
echo date('h:m:s', $diff_time_abs_seconds);
}

Categories