I'm using MySQL and Hibernate Envers to log audity info, it saves a timestamp in a numeric format, how can i convert this timestamp to date in MySQL, not in Java?
Thanks!
UPDATE -
You can use FROM_UNIXTIME() in-built function.
http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_from-unixtime
Simply taking it into Date object, it should work -
Date date = resultSet.getTimestamp("timestamp");
I guess this timestamp includes milliseconds, so you can simply divide this value by 1000 :
FROM_UNIXTIME(hr.`TIMESTAMP`/1000)
Formatted:
DATE(FROM_UNIXTIME(hr.`TIMESTAMP`/1000))
OR
DATE_FORMAT(FROM_UNIXTIME(hr.`TIMESTAMP`/1000) ,'%Y-%m-%d %H:%i:%s')
Related
I have a database field timestamp without timezone, that has values like 2015-11-23 14:42:55.278.
Now I want to find database records with just using the date part 2015-11-13.
Is that possible?
Ideally using hibernate and spring.
I'm not sure if is the best way in performace terms, but you may search dates between 2015-11-23 00:00:00.000 and 2015-11-23 23:59:59.999
If you want to fetch only for day 2015-11-13 then you can fetch all records using between keyword and by using timestamp of start of day.
dateField between 2015-11-13:<time_of_beginning_of_day> AND 2015-11-14:<time_of_beginning_of_next_day>
or
dateField between 2015-11-13:<time_of_beginning_of_day> AND 2015-11-13:<time_of_end_of_day>
You can cast the column to a date, e.g:
Postgres specific:
the_timestamp_column::date = date '2015-11-13'
or (standard SQL)
cast(the_timestamp_column as date) = date '2015-11-13'
You can also "reduce" the timestamp to different levels using date_trunc()
http://www.postgresql.org/docs/current/static/functions-datetime.html#FUNCTIONS-DATETIME-TRUNC
One of my database column is of type Timestamp format (yyyy-MM-dd HH:mm:ss) but the data saved in it is 2014-06-13 00:00:00. So the time component is not saved to the database table.
I am trying to INSERT data to that table but unable to remove the time component from my data.
Here is what I am doing:
long time = System.currentTimeMillis();
java.sql.Timestamp timestamp = new java.sql.Timestamp(time);
So the time (long) = 1402710418003 and timestamp=2014-06-13 21:46:58.003
Is there a way I can remove the time part from timestamp?
Ex: 2014-06-13
OR
Ex: 2014-06-13 00:00:00
This is my prepared statement:
java.util.Date currentDate= new java.util.Date();
sql_statement4.setTimestamp(6,new Timestamp(currentDate.getTime()));
sql_statement4 is a PreparedStatement object.
I want the value to be in Timestamp format.
How do I do this?
You need to change the call (from your comment),
sql_statement4.setTimestamp(6,new Timestamp(currentDate.getTime()));
to
sql_statement4.setDate(6,new java.sql.Date(currentDate.getTime()));
I am trying to insert into a variable in MS- SQL database the current date and the time.
I use this format:
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
Calendar cal = Calendar.getInstance();
System.out.println(dateFormat.format(cal.getTime()));
and I get this as a result 2013-01-28 09:29:37.941
My field in the database is defined datetime and as I have seen in other tables which have the same field, the date and the time is written exactly like this 2011-07-05 14:18:33.000.
I try to insert into the database with a query that I do inside a java program, but I get this error
SQL Exception: State : S0003 Message: The conversion of a varchar
data type to a datetime data type of the value is out of range. Error
: 242
My query is like that:
query = "INSERT INTO Companies CreatedOn"+
"VALUES ('" + dateFormat.format(cal.getTime()) + "')"
but I don't understand what I am doing wrong.
According to the error description, you are inserting an incorrect type into the database. See JDBC to MSSQL. You should convert Calendar to Timestamp.
Try using:
PrepareStatement statement
= connection.prepareStatement("INSERT INTO Companies CreatedOn VALUES(?)");
java.sql.Timestamp timestamp = new java.sql.Timestamp(cal.getTimeInMillis());
statement.setTimestamp(1, timstamp);
int insertedRecordsCount = statement.executeUpdate();
First of all, do NOT use string concatenation. Have you ever heart about SQL injection?
Correct way how to do that is to use prepared statement:
Idea is you define statement with placeholders and than you define value for those placeholders.
See #Taky's answer for more details.
dateFormat#format this method returns formatted string not Date object. Database field is DateTime and it is expecting java.sql.Timestamp to be inserted there not String according to docs.
To conform with the definition of SQL DATE, the millisecond values
wrapped by a java.sql.Date instance must be 'normalized' by setting
the hours, minutes, seconds, and milliseconds to zero in the
particular time zone with which the instance is associated.
Try java.sql.Timestamp object instead of String in query and I'd recommend you to use PreparedStatement.
This is because you are trying to save String date value to Date type DB field.
convert it to Data dataType
You can also use the datetime "unseparated" format yyyymmdd hh:mm:ss
You could use Joda framework to work with date/time.
It maps own date/time types to Hibernate/SQL types without problem.
When you set parameters in HQL query joda carries about right type mapping.
If you want to store current date and time then you should use MYSQL inbuilt method NOW().
for brief documentation refer http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html . so your code will be like.
INSERT INTO Companies CreatedOn VALUES(NOW())"
However If you want to do it using java Date-util then it should be
Calendar cal = Calendar.getInstance();
java.sql.Timestamp timestamp = new Timestamp(cal.getTimeInMillis());
We have an app in which we are using hibernate with mysql db.
We have a db script import.sql which have some insert into statements and we also have some date fields in db like start_date end_date in which we are string dates in default format, that is,YYYY-MM-DD.
Now issue is at the time of retrieving/comparing dates hibernates showing strange behaviour for example suppose if we have a date 2012-01-30 then hibernate reads in proper format that is, Jan 30 2012, but if we have a date like 2012-02-06 then hibernate reads as June 02 2012. my DAO for comparing and retrieving result is as follows
public final List<Record> getPastRecords(final java.util.Date currentDate) {
List<Record> pastRecord = session.createCriteria(Record.class)
.add(Restrictions.lt("endTime", currentDate))
.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY).list();
return pastRecord;
}
Any idea what I am doing wrong?
without detailed code explanation guessing what may be the problem is very hard through i guess
it may be because of java.util.Date try to use java.sql.Date as when you call methods/constructors of libraries that deal with database better to use wrapper of java.util.Date which is java.sql.Date.
refer http://www.theresearchkitchen.com/archives/58
I have a MySQL table with one of the column type as Date. In my hibernate mapping file I have mapped this column to type java.util.Date. Now in HQL while trying to retrieve objects based on date equality I do not get any results if I set the Date using new Date(). If I normalize the date by setting hours, minutes and seconds to zero I get results. Is this required since I have declared the SQL column type to be a Date and not Timestamp?
Try java.sql.Date
Hopefully this will help you out with the date equality issue.
RDJ
I was able to use java.util.Date with a SQL Server Date column by explicitly setting the #Type:
#Type(type="date")
public java.util.Date getDate() {
return date;
}
Without the annotation, I was getting
java.lang.IllegalArgumentException: Timestamp format must be yyyy-mm-dd hh:mm:ss[.fffffffff]
with Hibernate 3.5.1-final