How to select by date only if field is a timestamp? - java

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

Related

Oracle session timezone: Can Oracle DB session convert java.sql.Date to correct timezone?

We have an audit table( Columns/Types: ID/Number,.. Audited_Date/Date) which logs audit entries using prepared statements. Until now, for different contexts we set the database session timezone for the connection, after which we were using the CURRENT_DATE attribute for the audited_date column. THIS MEANT THAT THE DATE INSERTED INTO THE COLUMN IS IN THE TIMEZONE OF THE CONNECTION WHICH IS IMPORTANT.
Now, we have a new requirement to add different dates based on the supplied timestamps for the audit logs. Similar to the previous approach where the auditing engine didn't have to worry about the timezone, is there a way to set the date for the column, WITHOUT having to do something like this:
TimeZone timeZone = TimeZone.getTimeZone(timezone);
calendar.setTimeZone(timeZone);
preparedStatement.setDate(4, new java.sql.Date(userTimestampMillis), calendar);
I would really like NOT to do this because the timezone attribute is decided based on multiple attributes like system environments, and other parameters. The application uses ALTER SESSION SET TIME_ZONE="CONTEXT_TIMEZONE" in a global scope of the application where connections are fetched from.
Is there any way to let the DB session handle the timezone conversion?
These two approaches fail to convert the the timestamp to the DB session timezone. If i'm not wrong, they are using the JVM timezone.
FAIL1.
Timestamp timestamp = new Timestamp(userTimestampMillis);
preparedStatement.setTimestamp(4, timestamp);
FAIL2.
preparedStatement.setObject(4, new java.sql.Date(userTimestampMillis));
Any documentation is greatly appreciated.
DATEs are not time zone aware, so you probably want to work with something in the TIMESTAMP WITH TIME ZONE data type. You say you can correctly set the database session time zone, so you're mostly there. Say you're in Los Angeles and my database session is in Chicago:
alter session set time_zone = 'America/Chicago';
Session altered.
select current_timestamp from dual;
CURRENT_TIMESTAMP
---------------------------------------------
2018-07-27 20:30:28.672000000 AMERICA/CHICAGO
select cast( current_timestamp at time zone 'America/Los_Angeles' as date ) as d from dual;
D
-------------------
2018-07-27 18:30:28
So you basically need to use AT TIME ZONE to convert the TIMESTAMP WITH TIME ZONE into the correct time zone, then use CAST ( ... AS DATE ) to turn that into a DATE, which basically just trucates off the time zone information and doesn't do any conversion.

Hibernate Envers Timestamp from revision date

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

Saving Timestamp data but only with date in Java

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()));

Java: Insert into a table datetime data

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());

mapping dates in hibernate and mysql

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

Categories