Converting seconds to Datetime in mysql - mysql

I am using JSP Servlets and have made a MySQL connection.
I have a value in seconds, which is basically the value of validity of a token.
I now want to convert this value and insert in Datetime format in MySQL.
So, bascially it should be something like
Datetime( Current Time + expiry_value_in_seconds )
How can I do this?

FoggyDay already answered how you can do it in Java, so I'll answer how to do it in MySQL specific SQL itself:
ADDDATE(current_timestamp, INTERVAL 10 second)

If you want to do it on the Java side, I'd use Calendar:
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.SECOND, expiry_value_in_seconds);
Here is a great tutorial:
Lars Vogel:
Java Date, Calendar and Time APIs
Otherwise, I'd use mySql DATE_ADD():
http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html
http://www.java2s.com/Tutorial/MySQL/0280__Date-Time-Functions/DATEADDcurdateINTERVAL1SECOND.htm

Related

node js Sequelize with MySQL date formate issue

I developed node js services with Sequelize with MySQL Everything working good. I am storing data in DB with date and time with service but if I get the same data with service, node js automatically converting time (a wrong format which is not in the database), I want same time which is present in the database. to solve this issue I set the timezone in services and in the database but none of them is working. can anyone provide me with the solution.
suggestion
you could include time format function in mysql
for example
SELECT TIME_FORMAT("19:30:10", "%H %i %s");
result
TIME_FORMAT("19:30:10", "%H %i %s")
19 30 10
ref
That's not the issue of node js , Sequelize by default gives the time in UTC , so that date time will be correct
Check : Just compare your date time with UTC , and check is that you are getting.
Solution : So what you can do is , just convert returned date and time to your timezone and you are good to go.
And that's a good practice if you are using UTC everywhere , you can get benefits when you are getting / showing in many countries.

CURRENT_TIMESTAMP in milliseconds in h2

The question CURRENT_TIMESTAMP in milliseconds discussed how to "get milliseconds out of a timestamp in MySql or PostgreSql". But the methods in the answers don't work because H2 doesn't support MySQL methods like conv.
I want to use a variant of CURRENT_TIMESTAMP for the defaultValueComputed of my schema file.
How can I get the exact milliseconds of a timestamp in H2? I want it be a long. I also want the milliseconds returned to be in Unix time.
Here it is in my schema file:
<column name="create_time" type="long" defaultValueComputed="?"
<constraints nullable="false"/>
</column>
I have this DAO object:
public interface MyDao extends Transactional<MyDao> {
#SqlUpdate(
"INSERT INTO my_table "(id, create_time)" +
"VALUES (:id, :create_time)"
void insert(#BindBean MyObject myObject);
}
I looked at the "Time and Date Functions" section of http://www.h2database.com/html/functions.html and couldn't find anything that could do this though maybe PARSEDATETIME somehow could work.
EDIT: Maybe an alias is possible. See groups.google.com/forum/#!topic/h2-database/kziTTTNlB9o:
I'm porting an application to H2 that was initially written for MySQL
(the queries contain some MySQL-specific syntax). Probably the most
challenging part of getting the queries running on H2 has been the use
of the MySQL date functions like DATE(), UNIX_TIMESTAMP(), and
FROM_UNIXTIME(). The good news is: because H2 supports creating
aliases for these, I was able to write a very small Java class that
implements these MySQL functions for H2, and once I aliased them into
place, H2 runs just about all of our queries without modification.
I know this is old question but anyone like me, can be search answer for this question. We can get current time by millisecond with h2 DATEDIFF() function.
Fisrtly we pass current_timestamp and first date value and return type SECOND as a parameters like :
DATEDIFF('SECOND', DATE '1970-01-01', CURRENT_TIMESTAMP()) * 1000 the returned result is current_time's millisecond for us.
I've tried the other answer here and it wasn't accurate - there was a small diff between the result and the actual Unix timestamp.
This, however, seems to work:
SELECT EXTRACT (EPOCH from CURRENT_TIMESTAMP()) * 1000
It seems like in the other answer I get the timestamp in my local time zone (GMT+3 in my case), so it's not the same as the Unix timestamp (in milliseconds). in my answer, I get the result in UTC.

converting java time to sqldate in query

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.

DATE_ADD Returning NULL on production server, working in development

Development is localhost running version 5.6.16, production is 5.1.73-cll
The DATE_ADD of this query returns NULL on production, but in development is does exactly what I want it to(adds 90 minutes to the game_time column), The game_time column is a string that contains time in the following format: '21:00'.
This is the query:
SELECT TIME(game_time),
DATE_ADD(TIME(game_time),
INTERVAL 90 MINUTE),
TIME(NOW())
FROM games
What is going on? What am i doing wrong?
I know time should be in a TIMESTAMP, or TIME, but I'm working on someone elses code, I didn't start this from scratch myself.
I've also just noticed that TIME() returns different things, in development, TIME('21:00') returns 21:00:00.000000, in production I only get 21:00:00
Managed to get around, not pretty, but it works.
SEC_TO_TIME(TIME_TO_SEC(TIME(game_time))+5400)
You better develop with the same version as the production server:
Your old version will convert your TIME value to a date and because it's an invalid date, it will get NULL, see manual chapter Conversion Between Date and Time Types
Here's the relevant part:
Before 5.6.4, MySQL converts a time value to a date or date-and-time
value by parsing the string value of the time as a date or
date-and-time. This is unlikely to be useful. For example, '23:12:31'
interpreted as a date becomes '2023-12-31'. Time values not valid as
dates become '0000-00-00' or NULL.
Edit:
To get a TIME value with the desired result, you could use ADDTIME.
This could be working:
SELECT TIME(game_time),
ADDTIME (TIME(CONCAT(CURDATE(), ' ', game_time))),
'01:30:00'),
TIME(NOW())
FROM games
untested, because I have no such old MySQL version anymore.
Try moving the conversion to time outside the DATE_ADD:-
SELECT TIME(game_time), TIME(DATE_ADD(game_time, INTERVAL 90 MINUTE)), TIME(NOW())
FROM games
DATE_ADD works on a DATE or DATETIME field, and as it is you are passing it a TIME field.

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?