I have this query for MySQL database:
Article.where('DAY( created_at ) = DAY( ? )', day)
And I try to use the query above also in the PostgreSQL database, specifically I am trying something like this:
Article.where("DATE_PART('day', created_at) = DATE_PART('day', ?)", today)
But I am getting the error PGError: ERROR: function date_part(unknown, unknown) is not unique
Why is there that error? I thought I have the syntax by documentation...
It seems today is a string of the pattern YYYY-MM-DD. You could just extract the rightmost two characters, instead of casting to date and then extracting a number. Would be faster and simpler:
Article.where("date_part('day', created_at::date)::int
= right(?, 2)::int", today)
right() requires PostgreSQL 9.1 or later. In older version you can subsitute:
... = substring(?, 9)
Because you want characters 9 and 10.
This should work, too:
Article.where("date_part('day', created_at::date)::int
= date_part('day', ?::date)", today)
Note, that you must cast '2012-01-16' to date, not to interval. '2012-01-16'::interval would be nonsense.
According to the documentation there are two functions:
date_part(text, timestamp)
date_part(text, interval)
so database cannot choose which one you want. Cast the second parameter to timestamp, e.g. like this:
DATE_PART('day', created_at::interval) = DATE_PART('day', ?::interval)
Related
I have I'm having to workout the days difference between 2 columns one of which is a timestamp and the other being a varchar
timestamp - 2016-01-25 23:55:23 and varchar - 24/12/2015
not the best format for dates, but given that I'm unable to change the columns type is it possible to work out the difference in days between those 2 columns?
Many thanks
Max
The DateTime Class in PHP is very powerful and flexible, specially using the createFromFormat() method to load dates of different formats quite happily. Used together with the ->diff() method you should get what you want.
Here is an example
<?php
$ts = '2016-01-25 23:55:23';
$vc = '24/12/2015';
$tsdate = DateTime::createFromFormat('Y-m-d H:i:s', $ts);
$vcdate = DateTime::createFromFormat('d/m/Y', $vc);
$interval = $vcdate->diff($tsdate);
echo $interval->format('%R%a days');
Alternatively you could get MYSQL to do the heavy lifting and use its STR_TO_DATE() function when you query this odd varchar field
SELECT tsCol, STR_TO_DATE(varcharColumn, '%d/%m/%Y) as otherDate
Then when you see it in PHP it will be converted to a MySQL DATETIME column
Or going even further and getting MySQL to do all the work you could use MySQL's TIMESTAMPDIFF
SELECT TIMESTAMPDIFF(DAY, tsCol, STR_TO_DATE(varcharColumn, '%d/%m/%Y)) as differenceInDays;
Is there any sql command which I can insert into the stated query so I can convert the timestamp. Although it could be done separately which I have seen so far but I am trying to find something which I can add to the stated query as that would be helpful because I am using other queries to retrieve the data as well. If you any other questions please do mention. Addition: rating_timestamp contains both time and date.
SELECT rating_id,
rating_postid,
rating_posttitle,
rating_rating,
rating_timestamp,
rating_username,
rating_userid
FROM wp_ratings;
In cases of date arithmetic, it is especially important to specify the DBMS you are using - Oracle's math is different from Postgres' math is different from SQL Server's math is different from MySQL's math is...
This assumes that you are using SQL Server. Since there is no built in command to do this conversion, you need to create your own function to do that. The function below takes a UNIX / Linux timestamp and converts it to an SQL Server datetime.
CREATE FUNCTION dbo.fn_ConvertToLocalDateTime (#unixdate BIGINT)
RETURNS DATETIME
AS
BEGIN
DECLARE #UTCTimeOffset BIGINT
,#LocalDatetime DATETIME;
SET #UTCTimeOffset = DATEDIFF(second, GETUTCDATE(), GETDATE())
SET #LocalDatetime = DATEADD(second, #unixdate + #UTCTimeOffset, CAST('1970-01-01 00:00:00' AS datetime))
RETURN #LocalDatetime
END;
GO
I wast sure about about Sql version before. This worked perfectly for me.
FROM_UNIXTIME(rating_timestamp,'%h:%i:%s %D %M %Y')
java datetime (date.getTime()) is stored as string in mysql field.
How can we convert this to sql date using sql query. I am using mysql database.
Is there any sql function available?
For example - This is stored (1416231812348) for today's date in db.
Thanks for suggestions.
Java is returning the date as a long, to convert it you can use:
SELECT FROM_UNIXTIME(event_time) FROM MY_TABLE
If you get an error, try the following (after testing, I can see that your data is stored in milliseconds so you need to use this method):
SELECT FROM_UNIXTIME(event_time/1000) FROM MY_TABLE
(Change event_time to be the field name in your table and MY_TABLE to be the table name.)
Here is a SQLFiddle example that shows it working.
Here is an answer that gives you formatting options as well:
http://notsoyellowstickies.blogspot.co.uk/2011/11/converting-long-into-datetime-mysql.html
There is a java.sql package, that has time included. You can send it straight into your database without needing to convert it.
This may be a more pre-emptive solution than converting a date string from Java, into time in MySQL.
A similar question was answered and may be able to help you out here:
A datetime equivalent in java.sql ? (is there a java.sql.datetime ?)
most probably you have recorded from:
System.currentTimeMillis()
so:
select DATE_FORMAT ( from_unixtime( your_table_field / 1000 ) , '%e %b %Y');
you can change the date format as you like.
In MySQL using phpMyAdmin I am trying out this simple query to fetch rows that satisfy a certain date criteria:
select *
from student_invoice
where date_generated < '2012-01-01'
The date_generated is of date type. I get an error in phpMyAdmin that says:
ERROR: Unclosed quote # 64 STR: '
I have closed all quotes so its not making sense. The phpMyAdmin version is 2.11.9.6
Adding a new answer, as it's unrelated to my other one.
According to this bugzilla post here, your version suffers from this bug!
Upgrading to 2.11.11 or higher should fix this issue.
This may sound silly, but have you tried wrapping the date in double quotes?
SELECT *
FROM sometable
WHERE somedatecolumn < "2012-01-01"
Make sure that those are actually single quotes surrounding the date, not backticks.
Not familiar with the specific error. But you could try casting your static date to a date format, just to make sure it jives with the datecolumn format. Or even casting both? I.e:
where cast(somedatecolumn as DATE) < cast('2012-01-01' as DATE)
I have a feeling that won't work though. So maybe this?:
where somedatecolumn < cast('2012-01-01' as DATE)
It sounds more complicated than it actually is. Here is what I'm trying to do within the SELECT part:
SELECT TIMESTAMPADD(
UCASE(
SUBSTRING(offset_unit,1,CHAR_LENGTH(offset_unit)-1)
),1,'2003-01-02') as offset_date
offset_unit is a VARCHAR column in the database. It contains one of the following: "Hours","Minutes".
offset is an INT.
I am trying to convert the offset_unit to uppercase, after I have removed the last character ('s') so I can have a proper interval (MINUTE, HOUR...) so I can get a date that I can use in sorting afterwards, but MySQL keeps throwing an error. I have tested each step by adding one function at a time, and it only fails after I add TIMESTAMPADD. If I enter MINUTE manually then it works.
Any way to get this working?
Additional info: I am running this in CakePHP 1.3, in a find, within the 'fields' array, but that shouldn't be important.
this can be easily achived by using CASE WHEN clause as:
SELECT (CASE
WHEN offset_unit = 'HOURS'
THEN TIMESTAMPADD(HOUR,`offset`,'2003-01-02')
WHEN offset_unit = 'MINUTES'
THEN TIMESTAMPADD(MINUTE,`offset`,'2003-01-02')
END) AS offset_date
FROM my_table;
SEE SQLFIDDLE DEMO HERE
It doesn't work because TIMESTAMPADD does not take a string as the first argument, but a unit keyword, for example MINUTE. My guess is that you need to do this in two steps, first get the unit and then construct a query with the correct keyword.