How to add two times in PHP - php

I need to add two times and want to get total hours.
Here is my code:
foreach($result_data as $res) {
if( !empty($res['in1']) && !empty($res['out1']) ) {
$in1 = new DateTime($res['in1']);
$out1 = new DateTime($res['out1']);
$interval1 = $in1->diff($out1);
$h1 = $interval1->format('%H') . ":" . $interval1->format('%I');
$h2 = $h3 = "00:00";
if( !empty($res['in2']) && !empty($res['out2']) ) {
$in2 = new DateTime($res['in2']);
$out2 = new DateTime($res['out2']);
$interval2 = $in2->diff($out2);
$h2 = $interval2->format('%H') . ":" . $interval2->format('%I');
if( !empty($res['in3']) && !empty($res['out3']) ) {
$in3 = new DateTime($res['in3']);
$out3 = new DateTime($res['out3']);
$interval3 = $in2->diff($out3);
$h3 = $interval3->format('%H') . ":" . $interval3->format('%I');
}
}
$hours = strtotime($h1) + strtotime($h2) + strtotime($h3);
$res['total_hours'] = date("H:I", $hours);
$res_data[] = $res;
}
}
The error am getting is
date() expects parameter 2 to be integer, float given in
Can anyone please help me to find out the issue? Why $hours is float value?

Related

Codeigniter controller cronjob

Hello im using codeigniter and this controller file for cronjob but somehow public function fiveminutes work and gives response(ok) but public function daily doesn’t work and no responses or errors it should give “ok daily” response can someone help please ?? i couldn’t solve this
Hope someone fan help me because its realy important for me and my users
<?php
defined('BASEPATH') or exit('No direct script access allowed');
class Cronjob extends Guess_Controller
{
public function __construct()
{
parent::__construct();
$this->load->model(['m_admin', 'm_cronjob', 'm_leaderboard']);
}
public function fiveminutes()
{
if (time() >= $this->data['settings']['leaderboard_date']) {
$topClaimer = $this->m_leaderboard->getTopClaimer($this->data['settings']['admin_username']);
$topReferral = $this->m_leaderboard->getTopReferral($this->data['settings']['admin_username']);
$topFaucet = $this->m_leaderboard->getTopFaucet($this->data['settings']['admin_username']);
$topShortlink = $this->m_leaderboard->getTopShortlink($this->data['settings']['admin_username']);
$topOfferwall = $this->m_leaderboard->getTopOfferwall($this->data['settings']['admin_username']);
$activityRewards = explode('|', $this->data['settings']['activity_contest_reward']);
$referralRewards = explode('|', $this->data['settings']['referral_contest_reward']);
$faucetRewards = explode('|', $this->data['settings']['faucet_contest_reward']);
$shortlinkRewards = explode('|', $this->data['settings']['shortlink_contest_reward']);
$offerwallRewards = explode('|', $this->data['settings']['offerwall_contest_reward']);
$nextTime = (date("Y-m-d", strtotime('Sunday')) == date("Y-m-d", time())) ? strtotime('Sunday') + 7 * 86400 : strtotime('Sunday');
$this->m_cronjob->updateLeaderboardDate($nextTime);
$this->m_cronjob->resetLeaderboard();
$this->cache->delete('leaderboard_info');
if (!empty($this->data['settings']['activity_contest_reward'])) {
for ($i = 0; $i < min(count($activityRewards), count($topClaimer)); ++$i) {
$this->m_core->addNotification($topClaimer[$i]['id'], currency($activityRewards[$i], $this->data['settings']['currency_rate']) . " from Activity Contest was credited to your balance.", 1);
$this->m_cronjob->updateUserBalance($topClaimer[$i]['id'], trim($activityRewards[$i]));
$this->m_core->addOtherLog($topClaimer[$i]['id'], 'Activity contest #' . ($i + 1), trim($activityRewards[$i]));
}
}
if (!empty($this->data['settings']['referral_contest_reward'])) {
for ($i = 0; $i < min(count($referralRewards), count($topReferral)); ++$i) {
$this->m_core->addNotification($topReferral[$i]['id'], currency($referralRewards[$i], $this->data['settings']['currency_rate']) . " from Referral Contest was credited to your balance.", 1);
$this->m_cronjob->updateUserBalance($topReferral[$i]['id'], trim($referralRewards[$i]));
$this->m_core->addOtherLog($topReferral[$i]['id'], 'Referral contest #' . ($i + 1), trim($referralRewards[$i]));
}
}
if (!empty($this->data['settings']['faucet_contest_reward'])) {
for ($i = 0; $i < min(count($faucetRewards), count($topFaucet)); ++$i) {
$this->m_core->addNotification($topFaucet[$i]['id'], currency($faucetRewards[$i], $this->data['settings']['currency_rate']) . " from Faucet Contest was credited to your balance.", 1);
$this->m_cronjob->updateUserBalance($topFaucet[$i]['id'], trim($faucetRewards[$i]));
$this->m_core->addOtherLog($topFaucet[$i]['id'], 'Faucet contest #' . ($i + 1), trim($faucetRewards[$i]));
}
}
if (!empty($this->data['settings']['shortlink_contest_reward'])) {
for ($i = 0; $i < min(count($shortlinkRewards), count($topShortlink)); ++$i) {
$this->m_core->addNotification($topShortlink[$i]['id'], currency($shortlinkRewards[$i], $this->data['settings']['currency_rate']) . " from Shortlink Contest was credited to your balance.", 1);
$this->m_cronjob->updateUserBalance($topShortlink[$i]['id'], trim($shortlinkRewards[$i]));
$this->m_core->addOtherLog($topShortlink[$i]['id'], 'Shortlink contest #' . ($i + 1), trim($shortlinkRewards[$i]));
}
}
if (!empty($this->data['settings']['offerwall_contest_reward'])) {
for ($i = 0; $i < min(count($offerwallRewards), count($topOfferwall)); ++$i) {
$this->m_core->addNotification($topOfferwall[$i]['id'], currency($offerwallRewards[$i], $this->data['settings']['currency_rate']) . " from Offerwall Contest was credited to your balance.", 1);
$this->m_cronjob->updateUserBalance($topOfferwall[$i]['id'], trim($offerwallRewards[$i]));
$this->m_core->addOtherLog($topOfferwall[$i]['id'], 'Offerwall contest #' . ($i + 1), trim($offerwallRewards[$i]));
}
}
echo 'ok 1';
}
if ($this->data['settings']['lottery_duration'] > 0) {
if (time() >= $this->data['settings']['lottery_date']) {
$lotteries = $this->m_cronjob->getAllLottery();
if (count($lotteries) > 0) {
$luckyNumber = rand(0, count($lotteries) - 1);
$reward = count($lotteries) * $this->data['settings']['lottery_reward'] + $this->data['settings']['lottery_base_reward'];
$this->m_cronjob->updateUserBalance($lotteries[$luckyNumber]['user_id'], $reward);
$this->m_cronjob->insertLotteryHistory($lotteries[$luckyNumber]['user_id'], $lotteries[$luckyNumber]['number'], $reward);
$user = $this->m_core->get_user_from_id($lotteries[$luckyNumber]['user_id']);
$this->m_core->addNotification($user['id'], currency($reward, $this->data['settings']['currency_rate']) . " from Lottery was credited to your balance.", 1);
$this->m_core->addOtherLog($user['id'], 'Lottery', $reward);
}
$this->m_cronjob->updateLotteryDate(time() + 86400 * $this->data['settings']['lottery_duration']);
$this->m_cronjob->resetLottery();
echo 'ok 2';
}
}
$offerHistory = $this->m_cronjob->getAvailableOffers();
foreach ($offerHistory as $history) {
$this->m_cronjob->updateUserBalance($history['user_id'], $history['amount']);
$this->m_cronjob->updateOfferwallHistoryStatus($history['id']);
$user = $this->m_core->get_user_from_id($history['user_id']);
$this->m_core->addExp($user['id'], $this->data['settings']['offerwall_exp_reward']);
$user['exp'] += $this->data['settings']['offerwall_exp_reward'];
if ($user['exp'] >= ($user['level'] + 1) * 100) {
$this->m_core->levelUp($user['id']);
}
}
echo 'ok 3';
$currencies = $this->m_cronjob->getCurrencyName();
$currencyName = [];
foreach ($currencies as $currency) {
array_push($currencyName, $currency['currency_name']);
}
if (!in_array("bitcoin", $currencyName)) {
array_push($currencyName, 'bitcoin');
}
$query = urlencode(implode(',', $currencyName));
$apiUrl = 'https://api.coingecko.com/api/v3/simple/price?ids=' . $query . '&vs_currencies=usd';
$result = #json_decode(get_data($apiUrl), TRUE);
foreach ($result as $name => $price) {
$this->m_cronjob->updatePrice($name, $price['usd']);
}
if (isset($result['bitcoin']) && isset($result['bitcoin']['usd'])) {
$this->m_cronjob->updateBtcPrice($result['bitcoin']['usd']);
}
echo 'ok 4';
}
public function daily()
{
$yesterday = strtotime('yesterday midnight');
$today = strtotime('today midnight');
$date = date("Y-m-d", strtotime('yesterday midnight'));
$todayData = [
'date' => date("Y-m-d", $today)
];
$yesterdayData = [
'date' => $date
];
if ($this->m_cronjob->isYesterdayExist($date)) {
$this->db->insert('faucet_stats', $yesterdayData);
}
if ($this->m_cronjob->checkYesterdayLog($date)) {
$yesterdayData['active_users'] = $this->m_cronjob->countActiveUsers($yesterday, $today);
$yesterdayData['new_users'] = $this->m_cronjob->countNewUsers($yesterday, $today);
$faucetStat = $this->m_cronjob->faucetStat($yesterday, $today);
$yesterdayData['faucet_count'] = $faucetStat['cnt'];
$yesterdayData['faucet_amount'] = $faucetStat['amount'];
$shortlinkStat = $this->m_cronjob->shortlinkStat($yesterday, $today);
$yesterdayData['shortlink_count'] = $shortlinkStat['cnt'];
$yesterdayData['shortlink_amount'] = $shortlinkStat['amount'];
$offerwallStat = $this->m_cronjob->offerwallStat($yesterday, $today);
$yesterdayData['offerwall_count'] = $offerwallStat['cnt'];
$yesterdayData['offerwall_amount'] = $offerwallStat['amount'];
$offerwallStat = $this->m_cronjob->ptcStat($yesterday, $today);
$yesterdayData['ptc_count'] = $offerwallStat['cnt'];
$yesterdayData['ptc_amount'] = $offerwallStat['amount'];
$diceStat = $this->m_cronjob->diceStat($yesterday, $today);
$yesterdayData['dice_count'] = $diceStat['cnt'];
$yesterdayData['dice_amount'] = $diceStat['amount'];
$depositStat = $this->m_cronjob->depositStat($yesterday, $today);
$yesterdayData['deposit_count'] = $depositStat['cnt'];
$yesterdayData['deposit_amount'] = $depositStat['amount'];
$depositStat = $this->m_cronjob->withdrawStat($yesterday, $today);
$yesterdayData['withdraw_count'] = $depositStat['cnt'];
$yesterdayData['withdraw_amount'] = $depositStat['amount'];
$coinflipStat = $this->m_cronjob->coinflipStat($yesterday, $today);
$yesterdayData['coinflip_count'] = $coinflipStat['cnt'];
$yesterdayData['coinflip_amount'] = $coinflipStat['amount'];
$achievementStat = $this->m_cronjob->achievementStat($yesterday, $today);
$yesterdayData['achievement_count'] = $achievementStat['cnt'];
$yesterdayData['achievement_amount'] = $achievementStat['amount'];
$wheelStat = $this->m_cronjob->wheelStat($yesterday, $today);
$yesterdayData['wheel_count'] = $wheelStat['cnt'];
$yesterdayData['wheel_amount'] = $wheelStat['amount'];
$this->db->set('active_users', $yesterdayData['active_users']);
$this->db->set('new_users', $yesterdayData['new_users']);
$this->db->set('faucet_count', $yesterdayData['faucet_count']);
$this->db->set('faucet_amount', $yesterdayData['faucet_amount']);
$this->db->set('shortlink_count', $yesterdayData['shortlink_count']);
$this->db->set('shortlink_amount', $yesterdayData['shortlink_amount']);
$this->db->set('ptc_count', $yesterdayData['ptc_count']);
$this->db->set('ptc_amount', $yesterdayData['ptc_amount']);
$this->db->set('offerwall_count', $yesterdayData['offerwall_count']);
$this->db->set('offerwall_amount', $yesterdayData['offerwall_amount']);
$this->db->set('dice_count', $yesterdayData['dice_count']);
$this->db->set('dice_amount', $yesterdayData['dice_amount']);
$this->db->set('coinflip_count', $yesterdayData['coinflip_count']);
$this->db->set('coinflip_amount', $yesterdayData['coinflip_amount']);
$this->db->set('achievement_count', $yesterdayData['achievement_count']);
$this->db->set('achievement_amount', $yesterdayData['achievement_amount']);
$this->db->set('deposit_amount', $yesterdayData['deposit_amount']);
$this->db->set('deposit_count', $yesterdayData['deposit_count']);
$this->db->set('deposit_amount', $yesterdayData['deposit_amount']);
$this->db->set('withdraw_amount', $yesterdayData['withdraw_amount']);
$this->db->set('wheel_amount', $yesterdayData['wheel_amount']);
$this->db->set('wheel_count', $yesterdayData['wheel_count']);
$this->db->set('is_done', 1);
$this->db->where('date', $date);
$this->db->update('faucet_stats');
$this->db->insert('faucet_stats', $todayData);
$this->m_cronjob->clearHistory();
$this->db->set('wheel_cnt', 0);
$this->db->set('today_faucet', 0);
$this->db->update('users');
echo 'ok daily';
}
}
}
Most likely this function
if($this->m_cronjob->checkYesterdayLog($date))
results to false. I recommend that you should test this first.
if($this->m_cronjob->checkYesterdayLog($date)){
echo 'okay daily';
}else{
echo 'not okay, daily';
}
You can also check if the cronjob actually calls the daily function.

Fatal error : Using $this when not in object context in [duplicate]

This question already has answers here:
PHP Fatal error: Using $this when not in object context
(9 answers)
Closed 7 years ago.
I have the below function, But when I run the code make error like:
Fatal error: Using $this when not in object context in E:....
How to fix it. I replace $this-> with self:: but it failed too.
Please help in this regards,
<?php
function cehck_files()
{
$file1 = 'C:\xampp\htdocs\test\test1.php';
$file2 = 'C:\xampp\htdocs\test\test2.php';
$test = $this->compareFiles($file1,$file2,true);
$test_display = $this->toTable($test);
echo "<pre>";
print_r($test_display);
print_r($test);
echo "</pre>";
}
function compareFiles($file1, $file2, $compareCharacters = false) {
return $this->compare(file_get_contents($file1),file_get_contents($file2),$compareCharacters);
}
function compare($string1, $string2, $compareCharacters = false) {
$start = 0;
if ($compareCharacters){
$sequence1 = $string1;
$sequence2 = $string2;
$end1 = strlen($string1) - 1;
$end2 = strlen($string2) - 1;
} else {
$sequence1 = preg_split('/\R/', $string1);
$sequence2 = preg_split('/\R/', $string2);
$end1 = count($sequence1) - 1;
$end2 = count($sequence2) - 1;
}
// skip any common prefix
while ($start <= $end1 && $start <= $end2 && $sequence1[$start] == $sequence2[$start]) {
$start ++;
}
// skip any common suffix
while ($end1 >= $start && $end2 >= $start && $sequence1[$end1] == $sequence2[$end2]) {
$end1 --;
$end2 --;
}
// compute the table of longest common subsequence lengths
$table = self::computeTable($sequence1, $sequence2, $start, $end1, $end2);
// generate the partial diff
$partialDiff =
self::generatePartialDiff($table, $sequence1, $sequence2, $start);
// generate the full diff
$diff = array();
for ($index = 0; $index < $start; $index ++){
$diff[] = array($sequence1[$index], UNMODIFIED);
}
while (count($partialDiff) > 0) $diff[] = array_pop($partialDiff);
for ($index = $end1 + 1; $index < ($compareCharacters ? strlen($sequence1) : count($sequence1)); $index ++) {
$diff[] = array($sequence1[$index], UNMODIFIED);
}
// return the diff
return $diff;
}
function computeTable($sequence1, $sequence2, $start, $end1, $end2) {
$length1 = $end1 - $start + 1;
$length2 = $end2 - $start + 1;
// initialise the table
$table = array(array_fill(0, $length2 + 1, 0));
// loop over the rows
for ($index1 = 1; $index1 <= $length1; $index1 ++) {
// create the new row
$table[$index1] = array(0);
// loop over the columns
for ($index2 = 1; $index2 <= $length2; $index2 ++){
// store the longest common subsequence length
if ($sequence1[$index1 + $start - 1] == $sequence2[$index2 + $start - 1]) {
$table[$index1][$index2] = $table[$index1 - 1][$index2 - 1] + 1;
} else {
$table[$index1][$index2] =
max($table[$index1 - 1][$index2], $table[$index1][$index2 - 1]);
}
}
}
// return the table
return $table;
}
function generatePartialDiff( $table, $sequence1, $sequence2, $start ) {
$diff = array();
// initialise the indices
$index1 = count($table) - 1;
$index2 = count($table[0]) - 1;
// loop until there are no items remaining in either sequence
while ($index1 > 0 || $index2 > 0){
// check what has happened to the items at these indices
if ($index1 > 0 && $index2 > 0 && $sequence1[$index1 + $start - 1] == $sequence2[$index2 + $start - 1]) {
// update the diff and the indices
$diff[] = array($sequence1[$index1 + $start - 1], UNMODIFIED);
$index1 --;
$index2 --;
} elseif ($index2 > 0 && $table[$index1][$index2] == $table[$index1][$index2 - 1]) {
// update the diff and the indices
$diff[] = array($sequence2[$index2 + $start - 1], INSERTED);
$index2 --;
}else{
// update the diff and the indices
$diff[] = array($sequence1[$index1 + $start - 1], DELETED);
$index1 --;
}
}
// return the diff
return $diff;
}
function toTable($diff, $indentation = '', $separator = '<br>') {
$html = $indentation . "<table class=\"diff\">\n";
// loop over the lines in the diff
$index = 0;
while ($index < count($diff)){
// determine the line type
switch ($diff[$index][1]){
// display the content on the left and right
case UNMODIFIED:
$leftCell =
self::getCellContent(
$diff, $indentation, $separator, $index, UNMODIFIED);
$rightCell = $leftCell;
break;
// display the deleted on the left and inserted content on the right
case DELETED:
$leftCell =
self::getCellContent(
$diff, $indentation, $separator, $index, DELETED);
$rightCell =
self::getCellContent(
$diff, $indentation, $separator, $index, INSERTED);
break;
// display the inserted content on the right
case INSERTED:
$leftCell = '';
$rightCell =
self::getCellContent(
$diff, $indentation, $separator, $index, INSERTED);
break;
}
// extend the HTML with the new row
$html .=
$indentation
. " <tr>\n"
. $indentation
. ' <td class="diff'
. ($leftCell == $rightCell
? 'Unmodified'
: ($leftCell == '' ? 'Blank' : 'Deleted'))
. '">'
. $leftCell
. "</td>\n"
. $indentation
. ' <td class="diff'
. ($leftCell == $rightCell
? 'Unmodified'
: ($rightCell == '' ? 'Blank' : 'Inserted'))
. '">'
. $rightCell
. "</td>\n"
. $indentation
. " </tr>\n";
}
// return the HTML
return $html . $indentation . "</table>\n";
}
?>
You are using $this for a function which is not a method of any class.
Instead of
$test = $this->compareFiles($file1,$file2,true);
Use:
$test = compareFiles($file1,$file2,true);
Also, change
return $this->compare(file_get_contents($file1),file_get_contents($file2),$compareCharacters);
To
return compare(file_get_contents($file1),file_get_contents($file2),$compareCharacters);
And to the remaining changes in this way.

Set color shade based on variable number with PHP

Ok, I don't even know where to start with this one! I'll try and explain what I want to achieve, and we'll go from there....
I have a list of dates each with an associated number, say from 20-100. What I want to do is to output the date in a shade which represents the associated number. So 20 would display in a light blue and 100 in a dark blue. My code so far looks like this...
dateArray = Array('2001-01-01'=>30, '2001-02-01'=>40, '2001-03-01'=>50, '2001-04-01'=>60, '2001-05-01'=>70, '2001-06-01'=>80, '2001-07-01'=>90, '2001-08-01'=>90, '2001-09-01'=>80, '2001-10-01'=>70, '2001-11-01'=>60, '2001-12-01'=>50)
$maxNum = max($dateArray);
$minNum = min($dateArray);
foreach($dateArray AS $date => $num){
$lightest = 'rgb(204,204,255)';
$darkest = 'rgb(0, 0, 179)';
///magic that converts $num into $shade goes here///
echo "<span style='color:$shade'>$date</span><br>"
}
Any ideas? Thanks
I would do something like that :
$dateArray = Array('2001-01-01'=>30, '2001-02-01'=>40, '2001-03-01'=>50, '2001-04-01'=>60, '2001-05-01'=>70, '2001-06-01'=>80, '2001-07-01'=>90, '2001-08-01'=>90, '2001-09-01'=>80, '2001-10-01'=>70, '2001-11-01'=>60, '2001-12-01'=>50)
// get max and min values
$maxNum = max($dateArray);
$minNum = min($dateArray);
// set rgb values for max and min
$lightest = array(204, 204, 255);
$darkest = array(0, 0, 179);
foreach($dateArray AS $date => $num)
{
// get a "delta" where the current num value is
$delta = ($num / $maxNum) - $minNum;
// get a pro-rata values thanks to $delta
$shadesNum = array(
$delta * ($lightest[0] - $darkest[0]) + $darkest[0],
$delta * ($lightest[1] - $darkest[1]) + $darkest[1],
$delta * ($lightest[2] - $darkest[2]) + $darkest[2]
);
echo "<span style='rgb(".implode(',', $shadesNum).")'>$date</span><br>";
}
Some languages have a "lerp" function - linear interpolation. Quite useful.
My suggestion:
for ($x1=20; $x1<=100; $x1+=10)
echo $x1 . ": " . getshade($x1) . "<br />\n";
function getshade($num) {
$rlight = 204;
$glight = 204;
$blight = 255;
$rdark = 0;
$gdark = 0;
$bdark = 179;
$lightnum = 20;
$darknum = 100;
$k01 = ($num-$lightnum)/($darknum-$lightnum); // 0 to 1
$rshade = ilerp($rlight, $rdark, $k01);
$gshade = ilerp($glight, $gdark, $k01);
$bshade = ilerp($blight, $bdark, $k01);
return "rgb($rshade,$gshade,$bshade)"; }
function lerp($start, $end, $k01) { // linear interpolation
return $k01*$end + (1.0-$k01)*$start; }
function ilerp($start, $end, $k01) { // integer lerp
return intval($k01*$end + (1.0-$k01)*$start); }
EDIT: Same thing but better:
$rgblight = [204,204,255];
$rgbdark = [0,0,179];
$numlight = 20;
$numdark = 100;
for ($x1=20; $x1<=100; $x1+=10)
echo $x1 . ": " . getshade2($x1, $numlight, $numdark, $rgblight, $rgbdark) . "<br />\n";
function getshade2($num, $numlight, $numdark, $rgblight, $rgbdark) {
$k01 = ($num-$numlight)/($numdark-$numlight);
for ($i1=0; $i1<3; $i1+=1)
$rgb[$i1] = ilerp($rgblight[$i1], $rgbdark[$i1], $k01);
return "rgb({$rgb[0]},{$rgb[1]},{$rgb[2]})"; }

Number of intersections between 2 date ranges

I have 2 date ranges in my Codeigniter App, and i want to calculate the number of days that intersects between those to ranges. any ideas?
Date1start = YYYY-MM-DD;
Date1end = YYYY-MM-DD;
Date2start = YYYY-MM-DD;
Date2end = YYYY-MM-DD;
Something like this should work
$datetimeStart1 = new DateTime('2015-12-10');
$datetimeEnd1 = new DateTime('2015-12-20');
$datetimeStart2 = new DateTime('2015-12-12');
$datetimeEnd2 = new DateTime('2015-12-28');
// following http://stackoverflow.com/questions/325933/determine-whether-two-date-ranges-overlap
if ($datetimeStart1 < $datetimeEnd2 && $datetimeEnd1 > $datetimeStart2) {
echo min($datetimeEnd1,$datetimeEnd2)->diff(max($datetimeStart2,$datetimeStart1))->days+1;
} else {
echo 'no overlap';
}
Demo: http://3v4l.org/9Pecb
Only for PHP 5.2
$datetimeStart1 = new DateTime('2015-12-10');
$datetimeStart1 = $datetimeStart1->format('U');
$datetimeEnd1 = new DateTime('2015-12-20');
$datetimeEnd1 = $datetimeEnd1->format('U');
$datetimeStart2 = new DateTime('2015-12-12');
$datetimeStart2 = $datetimeStart2->format('U');
$datetimeEnd2 = new DateTime('2015-12-28');
$datetimeEnd2 = $datetimeEnd2->format('U');
// following http://stackoverflow.com/questions/325933/determine-whether-two-date-ranges-overlap
if ($datetimeStart1 < $datetimeEnd2 && $datetimeEnd1 > $datetimeStart2) {
echo round(
((min($datetimeEnd1,$datetimeEnd2)) - (max($datetimeStart2,$datetimeStart1))) / (60*60*24)) + 1;
} else {
echo 'no overlap';
}
Demo: http://3v4l.org/a1WLk
Write it easy:
$datetimeStart1 = new DateTime('2015-12-10');
$datetimeEnd1 = new DateTime('2015-12-20');
$datetimeStart2 = new DateTime('2015-12-12');
$datetimeEnd2 = new DateTime('2015-12-28');
$start = max($datetimeStart2,$datetimeStart1);
$end = min($datetimeEnd1,$datetimeEnd2);
echo $end >= $start ? $end->diff($start)->days+1 : "no overlap";

Converting Degree, Minutes, Seconds (DMS) to decimal in PHP

Currently, I'm learning to use Google Maps API. From what I read, the API require the latitude and longitude in Decimal Degree (DD).
In my database, the data is stored as DMS.
Example, 110° 29' 01.1"
I would to ask if you guys have any DMS to DD in php. And, the converter must accept from a single string like the example above.
Regards
You can try if this is working for you.
<?php
function DMStoDD($deg,$min,$sec)
{
// Converting DMS ( Degrees / minutes / seconds ) to decimal format
return $deg+((($min*60)+($sec))/3600);
}
function DDtoDMS($dec)
{
// Converts decimal format to DMS ( Degrees / minutes / seconds )
$vars = explode(".",$dec);
$deg = $vars[0];
$tempma = "0.".$vars[1];
$tempma = $tempma * 3600;
$min = floor($tempma / 60);
$sec = $tempma - ($min*60);
return array("deg"=>$deg,"min"=>$min,"sec"=>$sec);
}
?>
Here's one where you pass in the latitude,longitude in DMS values and returns the converted DMS string. Easy and simnple
function DECtoDMS($latitude, $longitude)
{
$latitudeDirection = $latitude < 0 ? 'S': 'N';
$longitudeDirection = $longitude < 0 ? 'W': 'E';
$latitudeNotation = $latitude < 0 ? '-': '';
$longitudeNotation = $longitude < 0 ? '-': '';
$latitudeInDegrees = floor(abs($latitude));
$longitudeInDegrees = floor(abs($longitude));
$latitudeDecimal = abs($latitude)-$latitudeInDegrees;
$longitudeDecimal = abs($longitude)-$longitudeInDegrees;
$_precision = 3;
$latitudeMinutes = round($latitudeDecimal*60,$_precision);
$longitudeMinutes = round($longitudeDecimal*60,$_precision);
return sprintf('%s%s° %s %s %s%s° %s %s',
$latitudeNotation,
$latitudeInDegrees,
$latitudeMinutes,
$latitudeDirection,
$longitudeNotation,
$longitudeInDegrees,
$longitudeMinutes,
$longitudeDirection
);
}
I wrote a PHP function that does what the question asks: converts a string in degrees/minutes/seconds into decimal degrees. It accepts a number of different formats for the string, and honors direction (NSEW).
Here is the code:
<?php
function convertDMSToDecimal($latlng) {
$valid = false;
$decimal_degrees = 0;
$degrees = 0; $minutes = 0; $seconds = 0; $direction = 1;
// Determine if there are extra periods in the input string
$num_periods = substr_count($latlng, '.');
if ($num_periods > 1) {
$temp = preg_replace('/\./', ' ', $latlng, $num_periods - 1); // replace all but last period with delimiter
$temp = trim(preg_replace('/[a-zA-Z]/','',$temp)); // when counting chunks we only want numbers
$chunk_count = count(explode(" ",$temp));
if ($chunk_count > 2) {
$latlng = $temp; // remove last period
} else {
$latlng = str_replace("."," ",$latlng); // remove all periods, not enough chunks left by keeping last one
}
}
// Remove unneeded characters
$latlng = trim($latlng);
$latlng = str_replace("º","",$latlng);
$latlng = str_replace("'","",$latlng);
$latlng = str_replace("\"","",$latlng);
$latlng = substr($latlng,0,1) . str_replace('-', ' ', substr($latlng,1)); // remove all but first dash
if ($latlng != "") {
// DMS with the direction at the start of the string
if (preg_match("/^([nsewNSEW]?)\s*(\d{1,3})\s+(\d{1,3})\s+(\d+\.?\d*)$/",$latlng,$matches)) {
$valid = true;
$degrees = intval($matches[2]);
$minutes = intval($matches[3]);
$seconds = floatval($matches[4]);
if (strtoupper($matches[1]) == "S" || strtoupper($matches[1]) == "W")
$direction = -1;
}
// DMS with the direction at the end of the string
if (preg_match("/^(-?\d{1,3})\s+(\d{1,3})\s+(\d+(?:\.\d+)?)\s*([nsewNSEW]?)$/",$latlng,$matches)) {
$valid = true;
$degrees = intval($matches[1]);
$minutes = intval($matches[2]);
$seconds = floatval($matches[3]);
if (strtoupper($matches[4]) == "S" || strtoupper($matches[4]) == "W" || $degrees < 0) {
$direction = -1;
$degrees = abs($degrees);
}
}
if ($valid) {
// A match was found, do the calculation
$decimal_degrees = ($degrees + ($minutes / 60) + ($seconds / 3600)) * $direction;
} else {
// Decimal degrees with a direction at the start of the string
if (preg_match("/^(-?\d+(?:\.\d+)?)\s*([nsewNSEW]?)$/",$latlng,$matches)) {
$valid = true;
if (strtoupper($matches[2]) == "S" || strtoupper($matches[2]) == "W" || $degrees < 0) {
$direction = -1;
$degrees = abs($degrees);
}
$decimal_degrees = $matches[1] * $direction;
}
// Decimal degrees with a direction at the end of the string
if (preg_match("/^([nsewNSEW]?)\s*(\d+(?:\.\d+)?)$/",$latlng,$matches)) {
$valid = true;
if (strtoupper($matches[1]) == "S" || strtoupper($matches[1]) == "W")
$direction = -1;
$decimal_degrees = $matches[2] * $direction;
}
}
}
if ($valid) {
return $decimal_degrees;
} else {
return false;
}
}
?>
Here it is on Github with test cases: https://github.com/prairiewest/PHPconvertDMSToDecimal
Solved.
<?php
function DMStoDD($input)
{
$deg = " " ;
$min = " " ;
$sec = " " ;
$inputM = " " ;
print "<br> Input is ".$input." <br>";
for ($i=0; $i < strlen($input); $i++)
{
$tempD = $input[$i];
//print "<br> TempD [$i] is : $tempD";
if ($tempD == iconv("UTF-8", "ISO-8859-1//TRANSLIT", '°') )
{
$newI = $i + 1 ;
//print "<br> newI is : $newI";
$inputM = substr($input, $newI, -1) ;
break;
}//close if degree
$deg .= $tempD ;
}//close for degree
//print "InputM is ".$inputM." <br>";
for ($j=0; $j < strlen($inputM); $j++)
{
$tempM = $inputM[$j];
//print "<br> TempM [$j] is : $tempM";
if ($tempM == "'")
{
$newI = $j + 1 ;
//print "<br> newI is : $newI";
$sec = substr($inputM, $newI, -1) ;
break;
}//close if minute
$min .= $tempM ;
}//close for min
$result = $deg+( (( $min*60)+($sec) ) /3600 );
print "<br> Degree is ". $deg*1 ;
print "<br> Minutes is ". $min ;
print "<br> Seconds is ". $sec ;
print "<br> Result is ". $result ;
return $deg + ($min / 60) + ($sec / 3600);
}
?>
If you also want to include the reference, you might want to use this function:
function DMStoDD($ref, $deg, $min, $sec)
{
$n = $deg + (($min * 60 + $sec) / 3600);
if (($ref == "S") or ($ref == "W")) {
return -$n;
} else {
return $n;
}
}
This works very well:
<?php echo "<td> $deg&#176 $min' $sec&#8243 </td>"; ?>
where deg, min and sec are the angular co-ordinates.

Categories