Datetime changing on JSON response - mysql

I am selecting start and end date of a project from project_stage named table.
Here is the table elements
stage_start_date stage_end_date planned_start_date planned_end_date
2019-01-28 10:12:01 2020-12-08 09:05:28 2019-01-12 01:01:00 2020-12-01 00:00:00
Here datatype is DATETIME
Here is the code
SELECT ps.stage_start_date AS actual_start_date,
ps.stage_end_date AS actual_end_date,
ps.stage_planned_start_date AS planned_start_date,
ps.stage_planned_end_date AS planned_end_date
FROM project_stage AS ps
JOIN map_project_user AS mpu ON mpu.user_id = 22 AND mpu.project_id = 1 AND mpu.tenant_id = ps.tenant_id AND ps.project_id = mpu.project_id;
Result on JSON response
{
"actual_start_date": "2019-01-28T04:42:01.000Z",
"actual_end_date": "2020-12-08T03:35:28.000Z",
"planned_start_date": "2019-01-11T19:31:00.000Z",
"planned_end_date": "2020-11-30T18:30:00.000Z"
}
Here date time is changing its not the actual datetime which is in the table,why the date is changing on result.Here is the expected output
Expected Result
{
"actual_start_date": "2019-01-28 10:12:01",
"actual_end_date": "2020-12-08 09:05:28",
"planned_start_date": "2019-01-12 01:01:00",
"planned_end_date": "2020-12-01 00:00:00"
}
MYSQL DATATYPE is DATETIME. Data base timezone is in UTC and System timezone is also showing UTC, How can I covert this datetime corresponding to timezone of users system

According to the data examples, the Timezone issue appears to be in the code that converts the SQL result to JSON. Since the time difference between the database and the JSON is -05:30, it seems that the "JSON transformer" assumes that the result of the SQL query is IST (UTC +05: 30) and converts the time to UTC (subtracts 5:30).
The correct fix should be done in the "JSON transformer". However, if the requirement is to achieve the "corrected date" by modifying the SQL query, you can use the CONVERT_TZ (dt, from_tz, to_tz) function. This adds +5:30 and "JSON transformer" subtracts 5:30 later resulting the time being unchanged.
Something like that:
SELECT DATE_FORMAT(CONVERT_TZ(ps.stage_start_date, '+00:00', '+05:30'), "%Y-%m-%d %H:%i:%s") AS actual_start_date,
DATE_FORMAT(CONVERT_TZ(ps.stage_end_date, '+00:00', '+05:30'), "%Y-%m-%d %H:%i:%s") AS actual_end_date,
DATE_FORMAT(CONVERT_TZ(ps.stage_planned_start_date, '+00:00', '+05:30'), "%Y-%m-%d %H:%i:%s") AS planned_start_date,
DATE_FORMAT(CONVERT_TZ(ps.stage_planned_end_date, '+00:00', '+05:30'), "%Y-%m-%d %H:%i:%s") AS planned_end_date
FROM project_stage AS ps
JOIN map_project_user AS mpu ON mpu.user_id = 22
AND mpu.project_id = 1
AND mpu.tenant_id = ps.tenant_id
AND ps.project_id = mpu.project_id;
Edit: Another option: simply add +5:30 to the dates:
SELECT ps.stage_start_date + interval 5 hour + 30 minute AS actual_start_date,
ps.stage_end_date + interval 5 hour + 30 minute AS actual_end_date,
ps.stage_planned_start_date + interval 5 hour + 30 minute AS planned_start_date,
ps.stage_planned_end_date + interval 5 hour + 30 minute AS planned_end_date
FROM project_stage AS ps
JOIN map_project_user AS mpu ON mpu.user_id = 22
AND mpu.project_id = 1
AND mpu.tenant_id = ps.tenant_id
AND ps.project_id = mpu.project_id;

Your backend changes the time format. Check you API which connects to the database.

Related

Convert mySQL query to KNEX

I am converting series of queries to Knex syntax.
I am having problem with this query:
SELECT id,reviewed,log_reference,CONVERT(notification USING utf8),create_time,update_time,store,user_id
FROM store_failure_log
WHERE reviewed = 0
AND create_time BETWEEN NOW() - INTERVAL 18 HOUR AND NOW();
More precisely this line:
SELECT id,reviewed,log_reference,CONVERT(notification USING utf8),create_time,update_time,store,user_id
I have this Knex in place:
knex('store_failure_log')
.select('id', 'reviewed', 'log_reference', 'CONVERT(notification USING utf8)', 'create_time', 'update_time', 'store', 'user_id').convert('notification USING utf8')
.where('reviewed', 0)
.where(knex.raw('create_time BETWEEN NOW() - INTERVAL 18 HOUR AND NOW()'))
that produces this sql query:
select `id`, `reviewed`, `log_reference`, `CONVERT(notification USING utf8)`, `create_time`, `update_time`, `store`, `user_id` from `store_failure_log` where `reviewed` = 0 and create_time BETWEEN NOW() - INTERVAL 18 HOUR AND NOW()
Problem is in the: Convert(notification USING utf8).
The query is not valid, since the Convert is in parentheses. How can I write it with the knex?
In general how do I include SQL function calls in the KNEX syntax?
You can use raw to include SQL function calls in your Knex query, like you've already done in your where:
knex('store_failure_log')
.select(knex.raw('id, reviewed, log_reference, CONVERT(notification USING utf8), create_time, update_time, store, user_id'))
.where('reviewed', 0)
.where(knex.raw('create_time BETWEEN NOW() - INTERVAL 18 HOUR AND NOW()'))
Here is fixed version of #Veve's answer with correct quoting of identifiers and knex.raw syntax:
knex('store_failure_log')
.select('id', 'reviewed', 'log_reference', knex.raw('CONVERT(?? USING utf8)', ['notification']), 'create_time', 'update_time', 'store', 'user_id')
.where('reviewed', 0)
.where(knex.raw('?? BETWEEN NOW() - INTERVAL 18 HOUR AND NOW()', ['create_time']))
https://runkit.com/embed/lh2i1qif7obx

Selecting rows that are within 2 hours from current time

I am using PHP with MySQL and would like to select rows that have a booking time within 2 hours from now. How do I compare what is in my database with the NOW() MySQL function?
I have columns pickupDate in the format yyyy-mm-dd and pickupTime in the format HH:mm (24-hour). I have tried creating a query with NOW() which returns the a 12-hour time as HH:mm:ss e.g. 2019-05-24 07:54:06 . I can't figure out how to format this to 19:54, or if I should use a different function instead.
For example, if the current date and time is 24/05/19 19:54:06, I would like to select rows between 19:54 and 21:54 on this date.
My table structure is:
referenceNo VARCHAR(100)
pickupDate DATE
pickupTime VARCHAR(100)
You need to create a DATETIME compatible value out of your pickupDate and pickupTime (which you can do by CONCATing them together), then you can compare that with a time range from NOW() to 2 hours later:
SELECT *
FROM yourtable
WHERE CONCAT(pickupDate, ' ', pickupTime) BETWEEN NOW() AND NOW() + INTERVAL 2 HOUR
Demo on dbfiddle
To add two hours in php
$hoursnow = date('H:i');
$timestamp = strtotime(date('H:i')) + 60*60*2;
$plusTwohours = date('H:i', $timestamp);
And $PlusTwohours using this variable frame the query like below
Sql Query:
$sqlQuery = 'select * from foodorder where pickupDate=DATE(NOW()) AND pickupTime>='.$hoursnow.' and pickupTime<='.$plusTwohours;
$result = mysql_query($sqlQuery);
variable $result will have the values of query
For Second Scenario: Adding hours to end of the day May 24 23:30:00
This should be handle by two different date for same column pickupDate
$d = new DateTime('2011-01-01 23:30:30');
$startDate = $d->format('Y-m-d H:i:s'); // For testing purpose assigned manually
$starttime = date('H:i');
// Here Process start, storing end date by adding two hours
$enddate1 = strtotime($startDate) + 60*60*2;
$enddate = date('Y-m-d', $enddate1); // Extracting date alone
$endtime = date('H:i', $enddate1); // Extracting time alone
Have to compare start and end date for column pickupDate, here is the query
$sqlQuery = "select * from foodorder where pickupDate>=DATE(".$startDate.") AND pickupDate<=DATE(".$enddate.") AND pickupTime>='".$starttime."' AND pickupTime<='".$endtime."'";
$result = mysql_query($sqlQuery);

SparkSQL between timestamp in where(filter) clause (V.S. In MySQL)

Describe:
I have a table with timestamp column and i want to get the number of values where the timestamp in specific time window.
My code is as shown in here:
String startTime = "2018-08-08 00:00:00";
String endTime = "2018-08-08 23:59:59";
productDF.where("CREATETIME >= '" + startTime + "' AND CREATETIME <= '" + endTime + "'").count();
I also tried between...and...sentence; and also:
productDF.where(unix_timestamp(col("CREATETIME"), "yyyy-mm-dd hh:mm:ss")
.cast("timestamp")
.between(
Timestamp.valueOf(startTime),
Timestamp.valueOf(endTime)
)).count();
The result i get is 6843.
But when i operate the sql sentence using Navicat:
SELECT COUNT(*) FROM my_table
WHERE CREATETIME BETWEEN '2018-08-08 00:00:00' and '2018-08-08 23:59:59';
it shows 7689.
Problem:
I want to know why i get the different results in Spark and Mysql.....what am i missing here??
Problem solved!
The problem happened because of the TIMEZONE.
In spark env., it get the timezone from_unixtime..So need to set the config.
.config("spark.sql.session.timeZone", "UTC")
But I still don't understand why the spark sql session flow the system timezone instead of just select from the column.....

Returning data where datetime columns are between user input of date, hours and minuets combined

I am having major issues with returning data from my table where dates are between six user inputs. A user can select a from date, from hours, from minuets along with to date, to hours and to minuets.The aim is, if the input is found in the table a Jquery alert is displayed.
My table has two "datetime" cols and contain the start date and time and the end date and time. i.e
Start date and time "2018-09-14 08:00:00"
End date and time: "2018-09-14 16:00:00"
On the user input form I have the following textfields:
RoomFromDate, date selected from a popup calander. The selected date
is at this stage in the format of "d-m-Y"
RoomToDate, date selected from a popup calander. The selected date is
at this stage in the format of "d-m-Y"
RoomFromTimeH, selected from a dropdown menu containing times in
hours from 00 to 23
RoomToTimeH, selected from a dropdown menu containing times in hours
from 00 to 23
RoomFromTimeM, selected from a dropdown menu containing times in
minuets from 00 to 59
RoomToTimeM, selected from a dropdown menu containing times in
minuets from 00 to 59
When the "RoomToTimeM" is selected it triggers a Jquery/Ajax script that posts the query information to a php script "check_record_avail.php" which runs the query and returns the data if a record is found.
Looking at the browser console I can see that the corret user selections are Posted via Ajax to "check_record_avail.php", see below.
console.log("Check date and time:",fromdate, fromhours, frommins, todate, tohours, tomins);
FromDate: 14-09-2018
FromTimeHours: 08
FromTimeMins: 00
ToDate: 14-09-2018
ToTimeHours: 16
ToTimeMins: 00
In my "check_record_avail.php" script I have the following:
if(isset($_POST['FromTimeHours'])){
$FromTime = $_POST['FromTimeHours'];
}
//echo "From time ". $FromTime."<br/>";
if(isset($_POST['FromTimeMins'])){
$FromTimeMins = $_POST['FromTimeMins'];
}
//echo "From time mins ". $FromTimeMins."<br/>";
if(isset($_POST['ToDate'])){
$ToDate = $_POST['ToDate'];
}
//echo "To date ". $ToDate."<br/>";
if(isset($_POST['ToTimeHours'])){
$ToTime = $_POST['ToTimeHours'];
}
if(isset($_POST['ToTimeMins'])){
$ToTimeMins = $_POST['ToTimeMins'];
}
$FromDateTime = $FromDate . " " . $FromTime . ":".$FromTimeMins.":00";
$ToDateTime = $ToDate . " " . $ToTime . ":".$ToTimeMins.":00";
//With the help of Stackoverflow member "scaisEdge" I have the follwong query:
SELECT ClientName, RoomName, RoomFromDateTime, RoomToDateTime FROM Conf
WHERE HotelID = '".$HotelID."' AND RoomID = '".$RoomID."' AND (RoomFromDateTime
BETWEEN str_to_date('".$FromDateTime ."', '%Y-%m-%d %T' ) AND str_to_date('".$ToDateTime."', '%Y-%m-%d %T'
OR RoomToDateTime BETWEEN str_to_date('".$FromDateTime ."','%Y-%m-%d %T' ) AND str_to_date('".$ToDateTime."','%Y-%m-%d %T' ))
If I hard code the selected user input using the following dates and times, From "2018-09-14 08:00:00", To "2018-09-14 16:00:00" the query looks like this:
SELECT ClientName, RoomName, RoomFromDateTime, RoomToDateTime FROM Conf
WHERE HotelID = 'EXBHX' AND RoomID = '3' AND (RoomFromDateTime
BETWEEN str_to_date('2018-09-15 08:00:00', '%Y-%m-%d %T' ) AND str_to_date('2018-09-15 16:00:00', '%Y-%m-%d %T' )
OR RoomToDateTime BETWEEN str_to_date('2018-09-15 08:00:00','%Y-%m-%d %T' ) AND str_to_date('2018-09-15 16:00:00','%Y-%m-%d %T' ))
Running this query returns 1 record.
However, if I change the "$FromTimeHours" to any hours time less than "16", the query returns zero records.
I have even tried converting all the datetimes into UNIX TimeStamps but the results are the same. Can anyone help me solve this issue.
Many thanks in advance of your time.
SELECT ClientName
, RoomName
, RoomFromDateTime
, RoomToDateTime
FROM Conf
WHERE HotelID = 'EXBHX'
AND RoomID = 3
AND RoomFromDateTime < '2018-09-15 16:00:00'
AND RoomToDateTime > '2018-09-15 08:00:00'

Compare dates from different years in mySQL

I'm getting a weird return when executing this query :
SELECT * FROM rrp
WHERE end > "2012-12-31"
nothing is returned, although I have one row on this table which "end" column is greater than "2012-12-31":
rrp
id_r | id__b | start | end | quantity
27 29 2012-01-01 2012-05-05 1
31 29 2012-11-01 2013-01-01 1
EDIT : startand endare date fields
EDIT : I used wrong database for my tests => wrong result
the issue was coming from Zend_Date when adding a day to a date:
$start = "2012-12-31";
$nStart = new Zend_Date($start, "YYYY-MM-dd");
$end = new Zend_Date($nStart);
$end->addDay(1);
When i echoed $end : echo $end->get("YYYY-MM-dd");
it outputs 2013-12-31
Most likely an issue with how the dates are formatted
This should help
http://dev.mysql.com/doc/refman/5.0/en/using-date.html
If end is a DATE column, it should work as expected:
SELECT
STR_TO_DATE('2013-01-01', '%Y-%m-%d') < "2012-12-31",
STR_TO_DATE('2012-05-05', '%Y-%m-%d') < "2012-12-31"
... returns 0, 1 in my box.
The only possible flaw I can think of is that your system's default date format is not %Y-%m-%d:
SELECT ##DATE_FORMAT
In that case, you need to specify a format every time:
SELECT *
FROM rrp
WHERE end > STR_TO_DATE('2012-12-31', '%Y-%m-%d')