php mysql time elapsed calculation - php

I have an app [iphone], that sends to a server some times [using json], so the times look like hh:mm 24 hour format,
the time gets saved in the db as varchar,
I need to calculate the elapsed time = endTime - startTime
but my problem is that I have the time in the db as varchar!, no time stamp,
so how to calculate the elapsed time, with out changing the varchar type of field in my db?,
can I convert this hh:mm to an int? for the operation?, and then showing it again as a hh:mm, possibly to save in other table?
thanks a lot!

so how to calculate the elapsed time, with out changing the varchar type of field in my db?
You can cast it, but you'd be better off having that as a datetime to start with.
cast(endtime as datetime) - cast(starttime as datetime) -- yields an interval

Easy:
$start_time = '11:10';
$end_time = '18:55';
$start_time = explode(':', $start_time);
$end_time = explode(':', $end_time);
$elapsed_time = $end_time[0]*60+$end_time[1]-$start_time[0]*60-$start_time[1];
// in minutes.
$elapsed_hours = floor($elapsed_time/60);
$elapsed_minutes = $elapsed_time-$elapsed_hours*60;
print $elapsed_hours.':'.$elapsed_minutes;
// 7:45

In PHP:
$json_time = '13:10';
$json_format = 'H:i';
$date = DateTime::createFromFormat($json_format, $json_time);
$mysql_format = 'Y-m-d H:i:s';
echo "Format: $mysql_format; " . $date->format($mysql_format) . "\n";
echo $date->getTimestamp();
Yeilds:
Format: Y-m-d H:i:s; 2011-06-08 13:10:00
1307495400

Related

How to get next time occurrence from now, submitted in php?

I have an input file with type time. what I want to do is to get time from the moment now that is if time right now is 2019-11-26 23:50:00 and the value of input field if 22:30:00, I should get a date 2019-11-27 22:30:00.
How can achieve this in PHP? in short, get the datetime stamp for the next occurrence of 22:30:00 which is 2019-11-27 22:30:00 as per the given example.
answer found but can we optimize the code more ?
$a = explode(':', date('H:i:s', strtotime($validateData['time'])));
$str = '+'.$a[0].' hours '.$a[1].' minutes '.$a[2].' seconds';
$trigger_at = date(date('Y-m-d H:i:s', strtotime( $str, strtotime($validateData['date']))));
return $trigger_at;
This is simpler and a lot more readable
$time = "21:30:00"; // Time from input
$today = date("Y-m-d $time");
$tomorrow = date("Y-m-d H:i:s", strtotime($today)+86400);
$date = strtotime($today) < strtotime("now") ? $tomorrow : $today;
Explanation: We take timestamp at specified hour for today and tomorrow, if today timestamp has been passed, we use tomorrow timestamp. Simple. :)
All you are doing is appending (concatenating) a string onto another string.
$time = "22:30:00"; // This is the time you have
$date = date("Y-m-d"); // Right now in yyyy-mm-dd format.
$newdatetime = $date.' '.$time;
That will give you the current date with the supplied time appended to it. You can convert that back into a timestamp using:
$timestamp = strtotime($newdatetime);
The answer below is based on the original question in which the time was assumed to be an offset from now. It is left here simply to avoid deleting a lot of code.
The function strtotime is easy to use for that. However, it doesn't accept HH:MM:SS format. So, you have to alter the string. I would do it like:
$time = "22:30:00"; // This is the time you have
$a = explode(':', $time);
$str = '+'.$a[0].' hours '.$a[1].' minutes '.$a[2].' seconds'; // This breaks it into separate numbers with labels.
$date = date("Y-m-d h:i:s", strtotime($str)); // The adjusted date
You can change the format of the output as you like by changing the first string used in the date function.

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);

Date is different when converted

hello i am working with the Date() function i am getting a time that is current and time that is coming from a database to compare the times, but the dates are different:
date_default_timezone_set("America/Los_Angeles"); // set time zone to LA
$date = date("m-d-Y h:i:s"); // current time
$current_time = strtotime($date); // current time in seconds
$get_time = 1357487529; //linux time from the server
$difference = $current_time - $get_time; //seconds that have pass already
$get_date = date("m-d-Y h:i:s", $get_time); // convert the linux time to current time and date
$exploded_get_date = explode(" ", $get_date); //divide the get date into 2 parts by space 0 = date 1 = time
$exploded_current_date = explode(" ", $date); //divide the current date into 2 parts by space 0 = date 1 = time
the results i get are:
01-Sun-2013 07:52:09 //get date
06-01-2013 07:56:25 //current date
1357487785 // current time
1357487529 // get time
256 //difference
why is it saying i have month 1 in the get date, but in the current date is actually month 6 and also the day it says it is Sunday 6, when is Saturday 1? how can i fix this?
m-d-Y is NOT a valid format for parsing. Only you Americans think it's sensible to put the elements in an unsorted order...
Anyway, the point is, what does 06-01-2013 mean? Is it June 1st, or January 6th?
For consistency's sake, the computer assumes January 6th (d-m-Y format).
I would strongly recommend using the Y-m-d H:i:s format, as this is inherently sortable as string due to being fully big-endian.
EDIT: It should be noted that you can just use time() to get the current timestamp.
Your code is VERY redundant:
$date = date("m-d-Y h:i:s"); // current time
$current_time = strtotime($date); // current time in seconds
can be replaced with a simple
$current_time = time();
and
$get_date = date("m-d-Y h:i:s", $get_time); // convert the linux time to current time and date
$exploded_get_date = explode(" ", $get_date); //divide the get date into 2 parts by space 0 = date 1 = time
$exploded_current_date = explode(" ", $date);
could just be
$exploded_date = date('m-d-y', $get_time);
$exploded_time = date('h:i:s', $get_time);
You are wasting a considerable amount of CPU cycles on useless/repetitive and ultimately redundant operations.
And in the greater picture, your error is that PHP's normal and easiest analysed/parsed date/time strings are in yyyy-mm-dd format. You're building mm-dd-yyyy, which is pretty much entirely scrambled. PHP cannot guess properly when you feed it uncertain formats. That means strtotime() is going to screw up and give you incorrect results.

PHP Diff Partial Datetime

I'm trying to subtract the time difference between the current datetime, and a time stated in my database. The datetimes current format is yyyy:mm:dd hh:mm:ss, however for this specific case i just want to subtract the time and not the date so i only want hh:mm:ss to be calculated and then stored into a different variable i can use and format how i want. Is it possible to take a full datetime, break it apart and do a diff on it? I think this is kind of confusing so ask if you need clarification. Here's what i've tried thus far:
<?php
//The time in the database
$classTime = DateTime::createFromFormat('Y-m-d H:i:s', '0000-00-00 18:30:00');
$timein = new DateTime("now", new DateTimeZone('America/Detroit'));
$timein->getTimestamp();
$timeout = $classTime;
$totaltime = $timeout->diff($timein);
$totaltime = $totaltime->format('Y-m-d H:i:s');
$totaltime = date('0000:00:00 H:i:s', strtotime($totaltime));
//I create a new date because i'm storing this time into the database, which can't be done with a datetime.
//FORMAT TIMES
$timein = $timein->format('Y-m-d H:i:s');
$timeout = $timeout->format('Y-m-d H:i:s');
echo "Time in " . $timein . " Time Out " . $timeout . " Total Time " . $totaltime;
?>
This current output returns:
Time in 2013-04-02 14:05:32 Time Out -0001-11-30 18:30:00 Total Time 0000:00:00 00:00:00
But i want it to return something like:
Time in 2013-04-02 14:05:32 Time Out -0000-00-00 18:30:00 Total Time 0000:00:00 03:30:00
Your question isn't very clear and I spent quite a bit of time answering the wrong question until I took a careful look at your code to see what you actually wanted.
As far as I understand it you store the finishing time of a lesson in your database as a MySql Datetime type and you want to find the time remaining between now and the time the lesson ends.
I'll ignore timezones for the purpose of this answer.
You start with
$classTime = DateTime::createFromFormat('Y-m-d H:i:s', '0000-00-00 18:30:00');
To do a meaningful time comparison, the date portion of $classTime needs to be set to today:-
$timeIn = new DateTime();
$year = (int)$timeIn->format('Y');
$month = (int)$timeIn->format('m');
$day = (int)$timeIn->format('d');
$classTime->setDate($year, $month, $day);
You can then do the comparison:-
$diff = $timeIn->diff($classTime);
$diff is now an instance of DateInterval.
We can now echo out the information:-
$start = $timeIn->format('Y-m-d H:i:s');
$end = $classTime->format('Y-m-d H:i:s');
$duration = $diff->format("%Hh, %Im, %Ss");
echo "Time in: $start, Time out: $end, Duration: $duration";
Which at the time I ran the code, gave the following output:-
Time in: 2013-04-05 13:22:54, Time out: 2013-04-05 18:30:00, Duration: 05h, 07m, 06s

Categories