How to convert java.util.Date into current time in timestamp..? - java

i am making a program in java.
i am using the following code
u.setLastlogin(new java.util.Date());
above function accepts parameter as java.util.Date but i want to store this value in a database table where the column is of type timestamp?
can any one help how to code so that i can insert the current timestamp of the system in the table. thanks.

You can convert Date to Timestamp as follows:
Timestamp timestamp = new Timestamp(date.getTime());
And if you want timestamp of current date:
new Timestamp(System.currentTimeMillis())

Date now = new Date();
now.getTime();

With JPA:
annotate lastLogin with: #Temporal(TemporalType.TIMESTAMP)
With JDBC:
PreparedStatement#setTimestamp

use this to java.sql.Timestamp timestamp = new java.sql.Timestamp(new Date().getTime());
u.setLastlogin(timestamp);

You could also just issue an SQL statement:
UPDATE MY_TABLE SET LAST_LOGIN = NOW();
This is for MySQL. You should also find this helpful: MySQL Date and Time functions
EDIT
As Rambo requested, setting default value of a column to the actual timestamp (As per MySQL: ALTER TABLE syntax and MySQL Data type default values):
ALTER TABLE MY_TABLE ALTER MY_TIMESTAMP COLUMN SET DEFAULT CURRENT_TIMESTAMP;

Related

HQL query ignores time portion of the Date object

I have problem with HQL where I am setting the query parameters. One of them is Date. When I debug the code there is Date with time entering the method. I set the parameter using setParameter(timestamp, new Timestamp(date.getTime())) or query.setTimestamp...etc etc I used many combinations...
When I use p6spy to examine the SQL comming from app to the DB there is only '29-Jan-21' or other date without time.
I am using hibernate 5.1.0 final and postgre DB. I'll be glad for any help.
Example:
Query query = getSessionFactory().getCurrentSession().createQuery("SELECT user FROM UserEntity cr WHERE user.userStatus.id = :statusId AND :timestamp >= user.valid_to");
This is how I tried to set the timestamp parameter:
query.setParameter("timestamp", new Timestamp(date.getTime()));
query.setParameter("timestamp", date, TimestampType.INSTANCE);
query.setTimestamp("timestamp", date);
query.setTimestamp("timestamp", new Timestamp(date.getTime()));
Problem is that the generated SQL replace timestamp by '29-Jan-21' or other date I choose but without time. The date parameter comes to the method from UI and it contains full date with time.

Timestamp insert issue in Mysql from Oracle

I am trying to insert the timestamp value from oracle to mysql timestamp column.
oracle value is 2017-09-01 11:35:22.495000000 but while getting value from result set its giving 2017-09-01 11:35:22.495.
its stored in oracle using oracle.sql.timestamp and i cannot insert the value in mysql.so getting stringvalue or timestamp value from oracle.sql.timestamp API.
But mysql storing the value is 2017-09-01 11:35:22.000495 and datatype defined as timestamp (6) and am not sure why its inserting the value like this?
How i can store the value in mysql similar to oracle ?
Using JDBC you should be able to directly copy a timestamp from one database to another doing something like this:
try(Connection oracleConnection = getOracleConnection();
Connection mysqlConnection = getMySQLConnection();
PreparedStatement oracleStmt = oracleConnection.prepareStatement("SELECT my_time FROM oracle_table");
PreparedStatement mysqlStmt = mysqlConnection.prepareStatement("INSERT INTO mysql_table VALUES (?)");
ResultSet rs = oracleStmt.executeQuery()) {
while(rs.next) {
mysqlStmt.setTimestamp(1, rs.getTimestamp("my_time"));
mysqlStmt.execute();
}
}
Timestamps are essentially numeric datatypes. Different DBMS's can have different precisions and different ways of handling timezones, but you shouldn't need any database specific API's to interact with them in most cases.
If you need to format a Timestamp you can use SimpleDateFormat on what you get back from getTimestamp() to format the string any way you need to.

Update timestamp in dynamoDB

I want CREATE_DATE and LAST_UPDATED fields in DynamoDB table. It is creating those fields with initial values for both fields as current date. But when some of the columns get updated it does not update the LAST_UPDATED column with new date.
I am using DynamoDBAutoGeneratedTimestamp annotation and both CREATE_DATE and LAST_UPDATED are of type java.util.date
#DynamoDBAutoGeneratedTimestamp(strategy=DynamoDBAutoGenerateStrategy.CREATE)
private Date CREATE_DATE;
#DynamoDBAutoGeneratedTimestamp(strategy=DynamoDBAutoGenerateStrategy.ALWAYS)
private Date LAST_UPDATED;
https://docs.aws.amazon.com/AWSJavaSDK/latest/javadoc/com/amazonaws/services/dynamodbv2/datamodeling/DynamoDBAutoGeneratedTimestamp.html.
Can anyone tell what else needs to be added if I am missing anything ?
Or I need to handle update date in code and it would not be auto populated?
Thank you

Generate Timestamp after converting to UTC Date

I am trying to insert datetime string value in Oracle Table on Timestamp(6) column.
But I am getting ORA-01843: not a valid month error.
Is there a way to this groovy specific without specifying oracle functions like to_date or to_timestamp?
2017-12-15 14:39:45
Yes, you can set session parameter:
alter session set nls_timestamp_format = 'YYYY-MM-DD HH24:MI:SS';
alter session set nls_date_format = 'YYYY-MM-DD HH24:MI:SS';
After you set this parameter you can enter your date as text string.
You can set these values also as Environment variable or in your Registry at HKLM\SOFTWARE\Wow6432Node\ORACLE\KEY_%ORACLE_HOME_NAME%, resp HKLM\SOFTWARE\ORACLE\KEY_%ORACLE_HOME_NAME%
Try using TO_TIMESTAMP:
SELECT
TO_TIMESTAMP ('2017-12-15 14:39:45', 'YYYY-MM-DD HH24:MI:SS')
FROM DUAL;
Demo

Hibernate insert default datetime to a not null column

In my table I have a column with following definition.
createdat DATETIME NOT NULL DEFAULT NOW(),
I'm trying to insert data in to this table using hibernate. I want this column to have default value. But it gives me exception
com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Column 'createdat' cannot be null
Any suggestions?
Just initiate your date object with new Date object in your POJO which is mapped in hibernate.
java.util.Date date = new java.util.Date();
I suppose you have your setters and getter for POJO, whenever you forgot or dont want to set date object this default date will be used

Categories

Resources