Convert TimeStamp to current timezone - php

I'm using the Bittrex REST API to find trades that occurred less than ten minutes ago:
https://bittrex.com/api/v1.1/public/getmarkethistory?market=BTC-ETH
Here are some of the trade timestamps that are returned from the endpoint:
2018-09-23T04:47:07.237
2018-09-23T04:47:02.797
Although today is actually 2018-09-22 where I live, it's showing these trades occurring in the future. Is the timezone different or something for these timestamps?
$now = date('m/d/y g:i a');
$now = strtotime($now);
$ten_minutes_ago = strtotime('-10 minutes');
foreach ($buy_sell_bittrex_orders['result'] as $buy_sell_bittrex_order) {
$buy_sell_bittrex_order_timestamp = $buy_sell_bittrex_order['TimeStamp'];
echo "Ten Minutes ago: " . $ten_minutes_ago . "<br>";
echo "Buy sell timestamp: " . $buy_sell_bittrex_order_timestamp . "<br>";
echo "Now: " . $now . "<br><br>";
if ( strtotime($buy_sell_bittrex_order_timestamp) >= $ten_minutes_ago && strtotime($buy_sell_bittrex_order_timestamp) <= $now ) {
// Do something
}
}
When I use the code above, none of the trades are found within 10 minutes ago, although there certainly must be. There can't have been trades that occurred in the future, so is there a timestamp issue here?
Here's an example of what the code above outputs:
Ten Minutes ago Bittrex: 1537679309
Buy sell timestamp: 1537704500
Now: 1537679940
In the example above, "Buy sell timestamp" is a higher value than "now" which represents the current day/time.
How can I convert the trade timestamps to match my current timezone? That seems to be the issue, though I may be wrong. Thanks!

You should provide the original Timezone and convert it to your Timezone.
See this Stackoverflow question and answer.
Convert time and date from one time zone to another in PHP
Good luck.

Related

PHP - Check if chosen time is at least 5 minutes into the future

In the application that I'm working on, the user must choose a date/time which is at least 5 minutes into the future. For this, I'm trying to implement a check. Below is the code which checks the time difference between the current time and chosen time.
$cur_date = new DateTime();
$cur_date = $cur_date->modify("+1 hours"); //fix the time since its an hour behind
$cur_date = $cur_date->format('m/d/Y g:i A');
$to_time = strtotime($chosen_date);
$from_time = strtotime($cur_date);
echo round(abs($from_time - $to_time) / 60,2). " minute"; //check the time difference
This tells me the time difference from the chosen time and the current time in minutes. So let's say the current time is 09/22/2015 5:53 PM and the chosen time is 09/22/2015 5:41 PM - it will tell me the difference which is 12 minutes.
What I want to know is how I can tell if those 12 minutes are into the future or in the past. I want my application to only proceed if the chosen time is at least 5 minutes into the future.
You're doing too much work. Just use DateTime() to do the date math for you:
// Wrong way to do this. Work with timezones instead
$cur_date = (new DateTime()->modify("+1 hours"));
// Assuming acceptable format for $chosen_date
$to_time = new DateTime($chosen_date);
$diff = $cur_date->diff($to_time);
if ($diff->format('%R') === '-') {
// in the past
}
echo $diff->format('%i') . ' minutes';
Demo
$enteredDate = new DateTime($chosen_date)->getTimestamp();
$now = new DateTime()->getTimestamp();
if(($enteredDate-$now)/60 >=5)echo 'ok';
Basically, the code takes the two dates converted in seconds since 1/1/1970. We calculate the difference between the two dates and divide the result by 60 as we want minutes. If there is a difference of at least 5 minutes, we're ok. If the number is negative, then we are in the past.
If anyone is looking to do something similar, I found the Carbon library which is included by default with the framework I am using (Laravel 5), it was much easier to do this calculation.
$chosen_date = new Carbon($chosen_date, 'Europe/London');
$whitelist_date = Carbon::now('Europe/London');
$whitelist_date->addMinutes(10);
echo "Chosen date must be after this date: ".$whitelist_date ."</br>";
echo "Chosen Date: ".$chosen_date ."</br>";
if ($chosen_date->gt($whitelist_date)) {
echo "proceed";
} else {
echo "dont proceed";
}

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

PHP Adding 15 minutes to Time value

I have a form that receives a time value:
$selectedTime = $_REQUEST['time'];
The time is in this format - 9:15:00 - which is 9:15am. I then need to add 15 minutes to this and store that in a separate variable but I'm stumped.
I'm trying to use strtotime without success, e.g.:
$endTime = strtotime("+15 minutes",strtotime($selectedTime)));
but that won't parse.
Your code doesn't work (parse) because you have an extra ) at the end that causes a Parse Error. Count, you have 2 ( and 3 ). It would work fine if you fix that, but strtotime() returns a timestamp, so to get a human readable time use date().
$selectedTime = "9:15:00";
$endTime = strtotime("+15 minutes", strtotime($selectedTime));
echo date('h:i:s', $endTime);
Get an editor that will syntax highlight and show unmatched parentheses, braces, etc.
To just do straight time without any TZ or DST and add 15 minutes (read zerkms comment):
$endTime = strtotime($selectedTime) + 900; //900 = 15 min X 60 sec
Still, the ) is the main issue here.
Though you can do this through PHP's time functions, let me introduce you to PHP's DateTime class, which along with it's related classes, really should be in any PHP developer's toolkit.
// note this will set to today's current date since you are not specifying it in your passed parameter. This probably doesn't matter if you are just going to add time to it.
$datetime = DateTime::createFromFormat('g:i:s', $selectedTime);
$datetime->modify('+15 minutes');
echo $datetime->format('g:i:s');
Note that if what you are looking to do is basically provide a 12 or 24 hours clock functionality to which you can add/subtract time and don't actually care about the date, so you want to eliminate possible problems around daylights saving times changes an such I would recommend one of the following formats:
!g:i:s 12-hour format without leading zeroes on hour
!G:i:s 12-hour format with leading zeroes
Note the ! item in format. This would set date component to first day in Linux epoch (1-1-1970)
strtotime returns the current timestamp and date is to format timestamp
$date=strtotime(date("h:i:sa"))+900;//15*60=900 seconds
$date=date("h:i:sa",$date);
This will add 15 mins to the current time
To expand on previous answers, a function to do this could work like this (changing the time and interval formats however you like them according to this for function.date, and this for DateInterval):
(I've also written an alternate form of the below function here.)
// Return adjusted time.
function addMinutesToTime( $time, $plusMinutes ) {
$time = DateTime::createFromFormat( 'g:i:s', $time );
$time->add( new DateInterval( 'PT' . ( (integer) $plusMinutes ) . 'M' ) );
$newTime = $time->format( 'g:i:s' );
return $newTime;
}
$adjustedTime = addMinutesToTime( '9:15:00', 15 );
echo '<h1>Adjusted Time: ' . $adjustedTime . '</h1>' . PHP_EOL . PHP_EOL;
get After 20min time and date
function add_time($time,$plusMinutes){
$endTime = strtotime("+{$plusMinutes} minutes", strtotime($time));
return date('h:i:s', $endTime);
}
20 min ago Date and time
date_default_timezone_set("Asia/Kolkata");
echo add_time(date("Y-m-d h:i:sa"),20);
In one line
$date = date('h:i:s',strtotime("+10 minutes"));
You can use below code also.It quite simple.
$selectedTime = "9:15:00";
echo date('h:i:s',strtotime($selectedTime . ' +15 minutes'));
Current date and time
$current_date_time = date('Y-m-d H:i:s');
15 min ago Date and time
$newTime = date("Y-m-d H:i:s",strtotime("+15 minutes", strtotime($current_date)));
Quite easy
$timestring = '09:15:00';
echo date('h:i:s', strtotime($timestring) + (15 * 60));

subtract time away from a php date time

I have a report I built but the problem is the datetimes in the database for the 3 major events are the same as the system processes then so fast, there is no easy way about it as I aggregate data from 4 servers into one jquery datatable and sort by date time decending.
So my question is how can I take a variable in PHP (string of mysql format date time), and reduce it by 1 second?
dognose answer is fine. Find below a method using DateTime.
For those who are not too confident about strtotime :-)
$string = "2013-06-26 18:00:00";
$date = DateTime::createFromFormat('Y-m-d H:i:s', $string);
$date->sub(new DateInterval('PT1S'));//substract 1 sec
echo $date->format('Y-m-d H:i:s'); //print : 2013-06-26 17:59:59
Doc about "PT1S" here (this can be read as Period Time 1 second)
use date along with strtotime should do the trick:
http://php.net/manual/de/function.strtotime.php
$string = "2013-06-26 18:00:00"; //can have any (valid) format
$subSeconds = 1;
$date = date("Y-m-d H:i:s", strtotime($string . " - {$subSeconds} second"));
echo $date."<br />"; //2013-06-26 17:59:59

Comparing DateTime?

I've been doing a good amount of research with this, and used a few codes to get to know how to make this work, but nothing has worked the way I wanted it to, or hasn't worked at all.
The code is:
<?php
$time1 = $user['last_active'];
$time2 = "+5 minutes";
if (strtotime($time1) > strtotime($time2)) {
echo "Online!";
}else{
echo "Offline!";
}
?>
It is supposed to compare the two variables, and find out if the last active variable is greater or less than 5 minutes, and if it is greater, appear offline. I do not know what's wrong as the NOW() updates on each page and stops if the user is not logged in. Any suggestions or help? Thanks.
The $time1 variable is coming from a fetched array that gets the ['last_active'] information that updates on each page.
I fixed my code, but it still doesn't work right, however, I think I have managed to get further than I was..
<?php
$first = new DateTime();
$second = new DateTime($user['last_active']);
$diff = $first->diff( $second );
$diff->format( '%H:%I:%S' );
if($diff->format( '%H:%I:%S' ) > (strtotime("5 minutes"))){
echo "Offline";
}else{
echo "Online";
}
?>
What can I do at this point?
Nobody pointed out that you actually have a bug. The "current time" will never be greater than "the current time +5 minutes"
Your first code sample will work right if you instead use "-5 minutes" as the "online threshold."
Also, comparing a timestamp without date to the output of strtotime() as you do in the second code is not a proper comparison. It has two problems:
Each time a new day comes around, the same time value will be repeated.
The output of strtotime is an integer representing seconds-since-epoch; the output of format() is a textual representation of hours:minutes:seconds within the current date.
As for your question how to calculate time between 2 dates / time, please view the solution on the following posts, that should give you enough information! (duplicate ? )
Calculate elapsed time in php
And here
How to get time difference in minutes in PHP
EDIT AS YOU PLEASE
<?
$first = new DateTime(); // this would hold your [last active]
//$first->modify("-6 minutes");
$second = new DateTime("NOW");
$difference = $second->diff( $first ); // second diff first
if ($difference->format('%i') > 5) { // comparing minutes only in example ( %i )
echo "The user is AFK";
} else {
echo "user might still be active";
}
?>

Categories