converting java time to sqldate in query - mysql

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.

Related

SQL Query nvarchar to date

I am working on SAP HANA Studio and have tried to run SQL command that converts an entire column of field, nvarchar, into one of field, date.
My dates have format: dd-mon-yyyy (i.e '29-Mar-1997') with field nvarchar(11).
I have looked at previous questions and SQL command documentation (for functions like CAST, CONVERT, TO_DATE, STR_TO_DATE) and have not gotten a solution.
Typical errors I get are: Function not recognized, or, Error while parsing Service Date as DATE at function to_date().
Any suggestions?
Thanks
-Diana
Try TO_DATE():
select to_date(col, 'DD-MON-YYYY')
Obviously your database driver/layer in SAP HANA does not support all mySQL functions.
Please connect to your database directly (using command-line or a gui like HeidiSQL) and create a view in your database:
CREATE VIEW view_tablename AS
SELECT STR_TO_DATE(`Service Date`, '%d-%b-%Y') AS ServiceDateDt, * FROM tablename
Then use view_tablename instead of tablename in all your queries - because view_tablename has the additional date field "ServiceDateDt".

Find output of MySQL inbuilt function in CLI using custom parameter

I want to see the working of MySQL functions FROM_UNIXTIME() and UNIX_TIMESTAMP() by providing the parameters to them myself in CLI, something like this:
SELECT UNIX_TIMESTAMP(1459460268);
without having to insert these custom values in a table first and then selecting them to see the output.
Thank you for your time :)
UNIX_TIMESTAMP function accepts a date and you are giving it UNIX TIMESTAMP. You can simply run this in MySQL CLI and get the results:
SELECT UNIX_TIMESTAMP("2016-04-01 03:07:48");
SELECT FROM_UNIXTIME(1459460268);
SELECT UNIX_TIMESTAMP();
The last one will return you the current UNIX TIMESTAMP.
Happy coding!

Converting Unix timestamp to actual Date and time

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')

Why does the Django time zone setting effect epoch time?

I have a small Django project that imports data dumps from MongoDB into MySQL. Inside these Mongo dumps are dates stored in epoch time. I would expect epoch time to be the same regardless of time zone but what I am seeing is that the Django TIME_ZONE setting has an effect on the data created in MySQL.
I have been testing my database output with the MySQL UNIX_TIMESTAMP function. If I insert a date with the epoch of 1371131402880 (this includes milliseconds) I have my timezone set to 'America/New_York', UNIX_TIMESTAMP gives me 1371131402, which is the same epoch time excluding milliseconds. However if I set my timezone to 'America/Chicago' I get 1371127802.
This is my code to convert the epoch times into Python datetime objects,
from datetime import datetime
from django.utils.timezone import utc
secs = float(epochtime) / 1000.0
dt = datetime.fromtimestamp(secs)
I tried to fix the issue by putting an explict timezone on the datetime object,
# epoch time is in UTC by default
dt = dt.replace(tzinfo=utc)
PythonFiddle for the code
I've tested this Python code in isolation and it gives me the expected results. However it does not give the correct results after inserting these object into MySQL through a Django model DateTimeField field.
Here is my MySQL query,
SELECT id, `date`, UNIX_TIMESTAMP(`date`) FROM table
I test this by comparing the unix timestamp column in the result of this query against the MongoDB JSON dumps to see if the epoch matches.
What exactly is going on here? Why should timezone have any effect on epoch times?
Just for reference, I am using Django 1.5.1 and MySQL-python 1.2.4. I also have the Django USE_TZ flag set to true.
I am no python or Django guru, so perhaps someone can answer better than me. But I will take a guess at it anyway.
You said that you were storing it in a Django DateTimeField, which according to the documents you referenced, stores it as a Python datetime.
Looking at the docs for datetime, I think the key is understanding the difference between "naive" and "aware" values.
And then researching further, I came across this excellent reference. Be sure the read the second section, "Naive and aware datetime objects". That gives a bit of context to how much of this is being controlled by Django. Basically, by setting USE_TZ = true, you are asking Django to use aware datetimes instead of naive ones.
So then I looked back at you question. You said you were doing the following:
dt = datetime.fromtimestamp(secs)
dt = dt.replace(tzinfo=utc)
Looking at the fromtimestamp function documentation, I found this bit of text:
If optional argument tz is None or not specified, the timestamp is converted to the platform’s local date and time, and the returned datetime object is naive.
So I think you could do this:
dt = datetime.fromtimestamp(secs, tz=utc)
Then again, right below that function, the docs show utcfromtimestamp function, so maybe it should be:
dt = datetime.utcfromtimestamp(secs)
I don't know enough about python to know if these are equivalent or not, but you could try and see if either makes a difference.
Hopefully one of these will make a difference. If not, please let me know. I'm intimately familiar with date/time in JavaScript and in .Net, but I'm always interested in how these nuances play out differently in other platforms, such as Python.
Update
Regarding the MySQL portion of the question, take a look at this fiddle.
CREATE TABLE foo (`date` DATETIME);
INSERT INTO foo (`date`) VALUES (FROM_UNIXTIME(1371131402));
SET TIME_ZONE="+00:00";
select `date`, UNIX_TIMESTAMP(`date`) from foo;
SET TIME_ZONE="+01:00";
select `date`, UNIX_TIMESTAMP(`date`) from foo;
Results:
DATE UNIX_TIMESTAMP(`DATE`)
June, 13 2013 13:50:02+0000 1371131402
June, 13 2013 13:50:02+0000 1371127802
It would seem that the behavior of UNIX_TIMESTAMP function is indeed affected by the MySQL TIME_ZONE setting. That's not so surprising, since it's in the documentation. What's surprising is that the string output of the datetime has the same UTC value regardless of the setting.
Here's what I think is happening. In the docs for the UNIX_TIMESTAMP function, it says:
date may be a DATE string, a DATETIME string, a TIMESTAMP, or a number in the format YYMMDD or YYYYMMDD.
Note that it doesn't say that it can be a DATETIME - it says it can be a DATETIME string. So I think the actual value being implicitly converted to a string before being passed into the function.
So now look at this updated fiddle that converts explicitly.
SET TIME_ZONE="+00:00";
select `date`, convert(`date`, char), UNIX_TIMESTAMP(convert(`date`, char)) from foo;
SET TIME_ZONE="+01:00";
select `date`, convert(`date`, char), UNIX_TIMESTAMP(convert(`date`, char)) from foo;
Results:
DATE CONVERT(`DATE`, CHAR) UNIX_TIMESTAMP(CONVERT(`DATE`, CHAR))
June, 13 2013 13:50:02+0000 2013-06-13 13:50:02 1371131402
June, 13 2013 13:50:02+0000 2013-06-13 13:50:02 1371127802
You can see that when it converts to character data, it strips away the offset. So of course, it makes sense now that when UNIX_TIMESTAMP takes this value as input, it is assuming the local time zone setting and thus getting a different UTC timestamp.
Not sure if this will help you or not. You need to dig more into exactly how Django is calling MySQL for both the read and the write. Does it actually use the UNIX_TIMESTAMP function? Or was that just what you did in testing?

ADDTIME and SEC_TO_TIME to SQL Server 2008

I try to change my code from MYSQL to SQL Server.
I have some problems with specific functions (ADDTIME and SEC_TO_TIME) in my query.
Here is the end of my query which i have to change :
order by j.idjour,j.heure,ADDTIME(j.heure,SEC_TO_TIME(pl.duree)) asc
I tried to use convert and DateAdd but i am a bit disapointed about how to change it without any error.
Thanks for your help.
This should be what you are looking for,
dateadd(second, pl.duree, j.heure)
Assuming that pl.duree is an integer value representing seconds and that j.heure is a time or datetime value.