Get time data from DB - Laravel - php

I want to give an alert when a condition is met in a day time, right now I get the hours statically
$hour1 = strtotime ("09:00");
$hour2 = strtotime ("01:00");
but I want to get the established schedule from the DB
$hour1 = strtotime ("09:00");
$hour2 = strtotime ("01:00");
if ($hour1 > $hour2) {
Session::flash('message', 'ABIERTO!');
Session::flash('', '');
}
elseif ($hour1 < $hour2 ) {
Session::flash('message', 'SHOP CLOSED!');
Session::flash('alert-class', 'alert-danger');
}
I already created the model on table status
help pls

You can try like this
$hour1 = DateTime::createFromFormat('H:i', $status->open);
$hour2 = DateTime::createFromFormat('H:i', $status->closed);
OR just simply
$hour1 = new DateTime($status->open);
$hour2 = new DateTime($status->closed);
Then just make conditional
if ($hour1 > $hour2)
// what to do

Related

Problem in checking when date and time has elapse using timezone

Am trying to create a date and time function to check if a given dateTime and timezone passed but my function is always returning true even when i put a future date.
I have below example class
<?php
class JobTimer{
public function __construct() {
}
public function isDateTime($startOn, $timezone = "GMT"){
$nowTime = new \DateTime("NOW", new \DateTimeZone($timezone));
$startTime = \DateTime::createFromFormat('M d, Y H:i:s', $startOn, new \DateTimeZone($timezone));
return ($nowTime >= $startTime ? true : false);
}
}
?>
Usage
Everything is returning true, my expectation is to return false if current time based on timezone has not yet elapse or return true when time has elapse or time is now
<?php
$job = new JobTimer();
//if($job->isDateTime("2019-05-02 12:00AM", "Asia/Kuala_Lumpur")){
//if($job->isDateTime("2021-05-02 12:00AM", "Asia/Kuala_Lumpur")){
if($job->isDateTime("2020-05-02 12:00AM", "Asia/Kuala_Lumpur")){
echo "YES";
}else{
echo "NO";
}
?>
In your JobTimer class $startTime is false because your format for DateTime::createFromFormat() does not match the format of the date you are passing in as a parameter and causing it to fail.
M d, Y H:i:s matches May 02, 2020 12:00:00 which is not what you are passing to that class.
You should be using:
$startTime = \DateTime::createFromFormat('Y-m-d H:iA', $startOn, new \DateTimeZone($timezone));
Working code:
class JobTimer{
public function __construct() {
}
public function isDateTime($startOn, $timezone = "GMT"){
$nowTime = new \DateTime("NOW", new \DateTimeZone($timezone));
$startTime = \DateTime::createFromFormat('Y-m-d H:iA', $startOn, new \DateTimeZone($timezone));
return $nowTime >= $startTime;
}
}
$job = new JobTimer();
if($job->isDateTime("2020-05-02 12:00AM", "Asia/Kuala_Lumpur")){
echo "YES";
}else{
echo "NO";
}
Output:
NO
Demo
Change your function to this:
public function isDateTime($startOn, $timezone = "GMT"){
$nowTime = new \DateTime("NOW", new \DateTimeZone($timezone));
$startTime = new \DateTime($startOn, new \DateTimeZone($timezone));
return ($nowTime >= $startTime ? true : false);
}
Your argument passed to createFromFormat is wrong, and therefore not creating a DateTime correctly. You can just pass your $startOn and a DateTimeZone to create a instance of DateTime

Get current date records from table with different time zone

This question is related to my previews one: How to change time zome in different tables in Laravel
After I mark the answer, discover a problem:
When user load the page it need to gives him records for the current day.
For example from 00:00:00 to now.
The problem is that the controller is asking the DB to give records from 00:00:00 in UTC, after this my model(in the link above) parsing it to LOCAL time.
This local time is Europe/Sofia (+3 hours), causing to miss 3 records from today starting with 03:00:00.
Any idea how to fix it?
The controller:
function getdata_chart(Request $request)
{
$start_date = date('d-m-Y 00:00:00');
$end_date = date('d-m-Y 23:59:59');
if($request->start_date != '' && $request->end_date != '')
{
// if user fill dates
$dateScope = array($request->start_date ." 00:00:00", $request->end_date ." 23:59:59");
} else {
// default load page - today
$dateScope = array($start_date, $end_date);
};
$students = MeasCanal::whereBetween('recordtime', $dateScope)
->selectRaw('recordtime')
->selectRaw('max(formattedvalue) filter (where fullname = \'Данни.Кота\') as iazovir')
->selectRaw('max(formattedvalue) filter (where fullname = \'Данни.Температура\') as temperatura350')
->where(function ($query) {
$query->where('fullname', 'like', "Язовир.Данни.Кота")
->orWhere('fullname', 'like', "ГСК_11_350.Данни.Температура");
})
->groupBy('recordtime')
->orderBy('recordtime')
->get();
return response()->json($students);
}
return response()->json($students);
}
The model:
class MeasCanal extends Model
{
protected $connection = 'MeasCanal';
protected $table = 'meas_kanal';
protected $fillable = ['fullname','formattedvalue','recordtime','qualitydesc','statedesc','id'];
/**
* Get the user's recordtime.
*
* #param string $value
* #return string
*/
public function getRecordtimeAttribute($value)
{
return Carbon::parse($value)->timezone('Europe/Sofia')->toDateTimeString();
}
}
You have to map the user input date from the DB timezone to the user timezone by calling the carbon method and array map function. and call the query as it is.
function getdata_chart(Request $request) {
$start_date = date('d-m-Y 00:00:00');
$end_date = date('d-m-Y 23:59:59');
if($request->start_date != '' && $request->end_date != '')
{
// if user fill dates
$dateScope = array($request->start_date ." 00:00:00", $request->end_date ." 23:59:59");
} else {
// default load page - today
$dateScope = array($start_date, $end_date);
};
$dbTimeZone = 'Asia/Kolkata'; // update with your db timezone
$userTimeZone = 'Europe/Sofia';
$dateScope = array_map(function($date) use ($dbTimeZone, $userTimeZone) {
return Carbon::createFromFormat('d-m-Y H:i:s', $date, $dbTimeZone)->setTimezone($userTimeZone);
}, $dateScope);
$students = MeasCanal::whereBetween('recordtime', $dateScope)
->selectRaw('recordtime')
->selectRaw('max(formattedvalue) filter (where fullname = \'Данни.Кота\') as iazovir')
->selectRaw('max(formattedvalue) filter (where fullname = \'Данни.Температура\') as temperatura350')
->where(function ($query) {
$query->where('fullname', 'like', "Язовир.Данни.Кота")
->orWhere('fullname', 'like', "ГСК_11_350.Данни.Температура");
})
->groupBy('recordtime')
->orderBy('recordtime')
->get();
return response()->json($students);
}
return response()->json($students);
}
Note that:- add the following line to the controller if you are not using carbon til yet.
use Carbon\Carbon;
The problem was that date separator was different on each fuction causing Unexpected data found.. After edit him the answer of Sachin Kumar did the job. Thanks for that.
Just discover the problem with similar long way solution:
$start_date0 = date('d-m-Y 00:00:00');
$end_date0 = date('d-m-Y 23:59:59');
$start_date = Carbon::createFromFormat('d-m-Y H:i:s', $start_date0, 'Europe/Sofia')->setTimezone('UTC');
$end_date = Carbon::createFromFormat('d-m-Y H:i:s', $end_date0, 'Europe/Sofia')->setTimezone('UTC');
if($request->start_date != '' && $request->end_date != '')
{
// if user fill dates
$start_date0 = $request->start_date;
$end_date0 = $request->end_date;
$start_date = Carbon::createFromFormat('d/m/Y H:i:s', $start_date0, 'Europe/Sofia')->setTimezone('UTC');
$end_date = Carbon::createFromFormat('d/m/Y H:i:s', $end_date0, 'Europe/Sofia')->setTimezone('UTC');
$dateScope = array($start_date, $end_date);
} else {
// default load page - today
$dateScope = array($start_date, $end_date);
};

How to convert ISO time inside DateTime to local time?

I create a DateTime object like this
$timestamp = new DateTime('2018-04-23T07:01:05.146000+00:00');
$timestampSql = $messageTimestamp->format('Y-m-d H:i:s');
I then insert the $timestampSql into a timestamp field in my mysql table. But the problem is, that the mysql thinks that this time and date is in whatever timezone the mysql server is, and doesn't realize, that it is in fact originating from an ISO time.
So basically, I need to somehow make sure the ->format outputs the timestamp converted to the current timezone the server is set to.
Here is a way you can easily switch a timezone using the dateTime Object:
function convertDate($dateTime){
$utc = 'UTC';
$newTimZone = 'TimeZone';
$newDateTime = new DateTime($dateTime, new DateTimeZone($utc));
$newDateTime->setTimezone(new DateTimeZone($newTimZone));
return $newDateTime->format('Y-m-d H:i:s');
}
Please check below function for server and user time zone
$time_diff = get_timezone_offset('America/New_York');
if(! function_exists('get_timezone_offset'))
{
/*get time differ user and server */
function get_timezone_offset($remote_tz, $origin_tz = null) {
if($origin_tz === null) {
if(!is_string($origin_tz = date_default_timezone_get())) {
return false; // A UTC timestamp was returned -- bail out!
}
}
$origin_dtz = new DateTimeZone($origin_tz);
$remote_dtz = new DateTimeZone($remote_tz);
$origin_dt = new DateTime("now", $origin_dtz);
$remote_dt = new DateTime("now", $remote_dtz);
$offset = $origin_dtz->getOffset($origin_dt) - $remote_dtz->getOffset($remote_dt);
$offset = $offset/60;
return $offset;
}
}
$current_date = date("Y-m-d h:i:sa");
$new_date = $this->time_differction($current_date,$time_diff);
if(! function_exists('time_differction'))
{
/*Return new date and time as per user time zone */
function time_differction($date_time, $time_diff){
$time = strtotime($date_time);
$time = $time - ($time_diff * 60 );
$date = date("Y-m-d H:i:s", $time);
return $date;
}
}

How to search a CSV file with php by checking if a date falls between 2 ranges

I made a previous post that was too vague. I've done a lot of research and think I can be more specific.
while (!feof($file_handle))
{
$loansinfo = fgetcsv($file_handle);
// Make sure we only check data for the game we posted
if($loansinfo[0]==$ID) {
$referenceDate = $WantedDate;
$fromDate = "$loansinfo[5]";
$toDate = "$loansinfo[6]";
// Convert dates to timestamps (strings to integers)
$referenceTimestamp = strtotime( $referenceDate );
$fromTimestamp = strtotime( $fromDate );
$toTimestamp = strtotime( $toDate );
$isBetween = $referenceTimestamp >= $fromTimestamp and $referenceTimestamp <= $toTimestamp;
//refuse booking
echo('<script type="text/javascript">alert("Game Already Booked");</script>');
exit;
}
}
// otherwise execute save code
Problem is, I always get 'Game already booked'. Why?
Sample CSV file data as requested:
ID, GameName,GameCost, DaysRequested, Total, ReservationStart, DateEnd
5,Pinball, 3.99,7, 27.99, 01/01/2015, 08/01/2015
Though it should be said that the form requires date entry as YYYY-MM-DD. I have java script that does the conversion.
I've seen this one! Try this:
while (!feof($file_handle)) {
$loansinfo = fgetcsv($file_handle);
if($loansinfo[0]==$ID){
$FromDate = "$loansinfo[5]";
$ToDate ="$loansinfo[6]";
if (strtotime($DateBorrowedFrom) <= strtotime($WantedDate)) {
if(strtotime($ToDate) >= strtotime($WantedDate)){
$CantBook = True;
}
}
else {
if (strtotime($DateBorrowedFrom) <= strtotime($DateTo)) {
$CantBook= true;
}
}
}
}
fclose($file_handle);
if($CantBook = true){
echo('<script type="text/javascript">alert("Game is already Booked");</script>');
}
else{
//Saving the booking
From the look of your code, you are not checking the result of $isBetween.
Here is a modified version that will get you a lot closer, assuming your dates are formatted correctly.
while (!feof($file_handle))
{
$loansinfo = fgetcsv($file_handle);
// Make sure we only check data for the game we posted
if($loansinfo[0]==$ID) {
$referenceDate = $WantedDate;
$fromDate = "$loansinfo[5]";
$toDate = "$loansinfo[6]";
// Convert dates to timestamps (strings to integers)
$referenceTimestamp = strtotime( $referenceDate );
$fromTimestamp = strtotime( $fromDate );
$toTimestamp = strtotime( $toDate );
$isBetween = $referenceTimestamp >= $fromTimestamp and $referenceTimestamp <= $toTimestamp;
if($isBetween == true) {
//refuse booking
echo('<script type="text/javascript">alert("Game Already Booked");</script>');
exit;
}
}
}

PHP if based on current system date

Trying to setup a page that auto updates based on the users date/time.
Need to run a promotion for 2 weeks and each day it needs to change the displayed image.
Was reading through http://www.thetricky.net/php/Compare%20dates%20with%20PHP to get a better handle on php's time and date functions.Somewhat tricky to test, but I basically got stuck on:
<?php
$dateA = '2012-07-16';
$dateB = '2012-07-17';
if(date() = $dateA){
echo 'todays message';
}
else if(date() = $dateB){
echo 'tomorrows message';
}
?>
I know the above function is wrong as its setup, but I think it explains what I am aiming for.
Time is irrelevant, it needs to switch over at midnight so the date will change anyway.
You seem to need this:
<?php
$dateA = '2012-07-16';
$dateB = '2012-07-17';
if(date('Y-m-d') == $dateA){
echo 'todays message';
} else if(date('Y-m-d') == $dateB){
echo 'tomorrows message';
}
?>
you want
<?php
$today = date('Y-m-d')
if($today == $dateA) {
echo 'todays message';
} else if($today == $dateB) {
echo 'tomorrows message';
}
?>
I would go a step back and handle it via file names. Something like:
<img src=/path/to/your/images/img-YYYY-MM-DD.jpg alt="alternative text">
So your script would look something like this:
<img src=/path/to/your/images/img-<?php echo date('Y-m-d', time()); ?>.jpg alt="alternative text">
If you're going to do date calculations, I'd recommend using PHP's DateTime class:
$promotion_starts = "2012-07-16"; // When the promotion starts
// An array of images that you want to display, 0 = the first day, 1 = the second day
$images = array(
0 => 'img_1_start.png',
1 => 'the_second_image.jpg'
);
$tz = new DateTimeZone('America/New_York');
// The current date, without any time values
$now = new DateTime( "now", $tz);
$now->setTime( 0, 0, 0);
$start = new DateTime( $promotion_starts, $tz);
$interval = new DateInterval( 'P1D'); // 1 day interval
$period = new DatePeriod( $start, $interval, 14); // 2 weeks
foreach( $period as $i => $date) {
if( $date->diff( $now)->format("%d") == 0) {
echo "Today I should display a message for " . $date->format('Y-m-d') . " ($i)\n";
echo "I would have displayed: " . $images[$i] . "\n"; // echo <img> tag
break;
}
}
Given that the promotion starts on 07-16, this displays the following, since it is now the second day of the promotion:
Today I should display a message for 2012-07-17 (1)
I would have displayed: the_second_image.jpg

Categories