Add 30 seconds interval in a given datetime - php

Need some help.
I am using PHP.
So I have coordinates data.
Specifically Longtitude and Latitude.
So let's say I have 15 data of Long and Lat to be inserted on a table.
However, the api gives me only a single datetime because these coordinates are in array.
For example:
[14.4364372;121.0125753, 14.4364375;121.0125755, 14.4364377;121.0125758, 14.436436;121.012574, 14.4364342;121.0125721, 14.4364326;121.0125704, 14.436433;121.0125707, 14.4364334;121.0125711, 14.4364338;121.0125716, 14.4364342;121.012572, 14.4364345;121.0125724, 14.4364348;121.0125728, 14.4364351;121.0125731, 14.4364353;121.0125733, 14.4364356;121.0125735]
So first you will explode it to get rid of the delimeter ','
And loop it to count how many are data,then explode again the delimiter ';' to count the long and lat given.
But it only have a single datetime.
What i want here is to insert these data including datetime but with interval of 30 seconds per insert.
How can i do that?
Expected output would be like this:
INSERT INTO table_gps(ticket,datetime,long,lat) VALUES(0,09/16/2016 03:30:26 pm, 14.4364363,121.0125745)
INSERT INTO table_gps(ticket,datetime,long,lat) VALUES(0,09/16/2016 03:30:56 pm, 14.4364364,121.0125746)
Here is my code:
$msg= 'YC GPS2~09/16/2016 13:29:46~-~[14.4364362;121.0125744, 14.4364363;121.0125745]';
if(strpos($msg,'YC GPS2')!==false){
//explode data
$explode=explode('~',$msg);
$ky=$explode[0];
$datetime=$explode[1];
$ticket=$explode[2];
$coords=$explode[3];
$coords=explode(',',$coords);
for($i=0;$i<count($coords);$i++){
$xpVal=$coords[$i];
if($xpVal){
$xp3=explode(';',$xpVal);
$lng=$xp3[0];
$lat=$xp3[1];
$lng=str_replace('[','',$lng);
$lat=str_replace(']','',$lat);
$time = date("m/d/Y h:i:s a", time() + 30);// where 30 is the seconds
echo "INSERT INTO GPS2(ticket,datetime,long,lat) VALUES(".$ticket.",".$time.",".$lng.",".$lat.") ";
}
}
}else{
echo '0';
}
Thanks.

In order to add how many seconds you want to particular date in PHP you can use the following.
$time = date("m/d/Y h:i:s a", time() + 30);// where 30 is the seconds
The following is really easy way to add days, minutes, hours and seconds to a time using PHP. Using the date function to set the format of the date to be returned then using strtotime to add the increase or decrease of time then after a comma use another strtotime passing in the start date and time.
//set timezone
date_default_timezone_set('GMT');
//set an date and time to work with
$start = '2014-06-01 14:00:00';
//display the converted time
echo date('Y-m-d H:i',strtotime('+1 hour +20 minutes',strtotime($start)));
Times can be entered in a readable way:
+1 day = adds 1 day
+1 hour = adds 1 hour
+10 minutes = adds 10 minutes
+10 seconds = adds 10 seconds

Related

php - Year Changed To The Current Year After Date Being Substituted

I am trying to set publish date based on user choice and give it interval in a loop. But after it is substituted with the intervals, the year changed to the current year.
Here is the sample of my code:
$datestart = "2012-03-06";
$datenow = date("$datestart H:i:s", current_time( 'timestamp' ));
$newpostdate1 = $datenow + strtotime("0 years 0 months 1 days 0 hours 0 minutes 0 seconds");
$newpostdate = date("Y-m-d H:i:s", $newpostdate1);
echo $datenow . " " . $newpostdate;
$datenow Will return 2012-03-06 16:19:33 while $newpostdate return the current date plus 1 day i.e: 2014-03-15 17:02:23.
Why $newpostdate returning the current date plus next 1 day instead of 2012-04-06 16:19:33 ?
..because what you're doing doesn't do what you think it does.
First, you set $datenow to a string (not a date object), with value "2012-03-06 " + the current time (assuming that's what current_time returns).
Then you call strtotime with the value "1 days" (well, your string has a bunch of other zero-valued fields, but they don't change the result), which returns the current time + 24 hours as a number (the number of seconds since 1970).
Then you take that value and add it with + to the above string. This causes the string to be interpreted as a number, so it turns into 2012 (and the rest of the string is ignored). So the result is a timestamp representing the current time + one day + 2,012 seconds - or one day, 33 minutes and 32 seconds from the time the code is run. Which you then format as a string.
You could use John Conde's solution to get a more meaningful result. (I assume your real problem is different, else why not just start out by setting the string to '2012-03-07' in the first place?)
The first parameter of date() is the format you want the timestamp passed as the second parameter to be displayed as. So basically you are using date() incorrectly.
I think this is what you are looking for:
$date = new DateTime($datestart);
$date->modify('+1 day');
echo $date->format(Y-m-d H:i:s);

time slice per day for two timestamps

I've two timestamps with a gap between a few hours and a few days.
Is there a way in PHP and / or MySQL to get the time slice for every day?
INPUT
Timestamp 1: 2013-10-30 10:00:00
Timestamp 2: 2013-10-31 11:00:00
OUTPUT
2013-10-30: 14 hours
2013-10-31: 11 hours
Easiest way to perform operations on dates is to convert them to timestamps.
Here, what you can do is to get three timestamps :
$ts1 = strtotime("2013-10-30 10:00:00");
$ts2 = strtotime("2013-10-31 00:00:00");
$ts3 = strtotime("2013-10-31 11:00:00");
$first_time_slice = ts2 - ts1; //here you got your first time slice in seconds, convert it to hours
$second_time_slice = ts3 - ts2; //idem for the second time slice
It can be done in MySql like this:
SELECT TIMEDIFF(TIMESTAMP(DATE('2013-10-30 10:00:00') + INTERVAL 1 DAY), '2013-10-30 10:00:00'),
TIMEDIFF('2013-10-31 11:00:00', TIMESTAMP(DATE('2013-10-31 11:00:00')))

comparing datetime is 1 hour ahead

I'm trying to count the rows with a datetime less that 10 minutes ago but the current time its being compared to seems to be 1 hour ahead so Imm getting 0 results, if I go into my table and put some fields forward an hour then I get results.
Getting results:
$stmt = $db->query('SELECT check_log FROM members WHERE check_log >= DATE_SUB(NOW(), INTERVAL 10 MINUTE)');
$row_count = $stmt->rowCount();
echo $row_count.' Members online.';
The datetime of the field of of typing this is 2013-07-11 16:54:12 and I'm getting no results but if I manually change the date time to 2013-07-11 17:54:12 I get 1 result the datetime was input seconds ago using:
$date = date("Y-m-d H:i:s");
The 17:54:12 is my local time and 16:54:12 seem to be my servers time, is my compare trying to look into the future or is it using my local time as a reference?
PHP and MySQL don't agree on the current timezone.
Pass the desired time in as a literal from PHP to SQL instead of using NOW().
Always store date times in php's timezone.
One function you can particularly make use of is strtotime.
$now = strtotime("now"); // current timestamp
$hour_later = strtotime("+1 hour"); // hour later
$now = date("Y-m-d H:i:s", $now);
$hour_later = date("Y-m-d H:i:s", $hour_later);

How can I identify the time after user update?

How can I identify the time passed after an user updated his account in my MySQL database? I have a timestamp in my MySQL table (to store user update time) so now how can I identify the time passed from last user update, using PHP?
As example:
User last update time: 2012-04-08 00:20:00;
Now: 2012-04-08 00:40:00;
Time passed since last update: 20 (minutes) ← I need this using PHP
If you have the data on
$last_update_time = '2012-04-08 00:20:00';
$now = time(); //this gets you the seconds since epoch
you can do
$last_update_since_epoch = strtotime($last_update_time); //this converts the string to the seconds since epoch
aand... now, since you have seconds on both variables
$seconds_passed = $now - $last_update_since_epoch;
now, you can do $seconds_passed / 60 to get the minutes passed since the last update.
Hope this helps ;)
In pseudo-code:
$get_user_time = mysql_query("SELECT timestamp FROM table");
$row = mysql_fetch_array($get_user_time);
$user_time = $row['timestamp']; //This is the last update time for the user
$now_unformatted = date('m/d/Y h:i:s a', time());
$now = date("m/d/y g:i A", $now_unformatted); // This is the current time
$difference = $now->diff($user_time); // This is the difference
echo $difference;
diff() is supported in >= PHP 5.3. Otherwise you could do:
$difference = time() - $user_time;
$secs=time()-strtotime($timestamp);
would give u number of seconds before it was updated and then you can convert this seconds into your needed time format like
echo $secs/60." minutes ago";
why not do it with mysql:
select TIMEDIFF(NOW(),db_timestamp) as time_past

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