JPA to_char function for date in Java - java

I have this query and an oracle DB. When I try to execute it, I never receive an answer from DB. Edit: Query return 0 rows. I know that is for Date because if I use the same query with TO_CHAR with Toad this works. How i can add in Java code TO_CHAR function? Thank you.
public List<PrivacySospensiva> getAllByCf(String cf,Long idsuperpratica,String stato,Date dataCensimento){
TypedQuery<PrivacySospensiva> query = entityManager.createQuery("select u from PrivacySospensiva u where u.id_superpratica = :idSuperpratica AND u.stato = :stato AND u.cf = :cf AND u.data_censimento = :dataCensimento", PrivacySospensiva.class);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH24:mm:SS");
sdf.format(dataCensimento);
query.setParameter("idSuperpratica", idsuperpratica);
query.setParameter("stato",stato);
query.setParameter("cf",cf);
query.setParameter("dataCensimento",dataCensimento);
List<PrivacySospensiva> result = query.getResultList();
return result;
}

The date format is wrong and should be yyyy-MM-dd HH:mm:ss (0-23 hours) or yyyy-MM-dd kk:mm:ss (1-24 hours). And SS would be microseconds.
Fortunately the code does not use it; all probably an experiment. One would need to do:
String t = sdf.format(dataCensimento);
query.setParameter("dataCensimento", t);
(sdf.format will not alter dataCensimento.)

Related

Get Now Date and Time

I'm using JPA and I want to store the date in this format dd/MM/yyyy HH:mm:ss
So I create a function
public static String getNowDate() {
Date date = new Date();
final DateFormat sdf = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
return sdf.format(date);
}
The problem is that this returns a String and I need a date.
#Temporal(TemporalType.TIMESTAMP)
private Date creationDate;
How do I make this work so I can save date and time exactly like that?
I know a easy solution is to declare creationDate as String. Is this too bad?
There is a problem with the premise to your question. Ideally, your current timestamp will be stored in a SQL database, in some sort of date column, and not as text. Since you are using JPA, backed by JDBC, you should just be inserting a date type. So, something like the following should work:
Timestamp timestamp = new Timestamp(System.currentTimeMillis());
// or maybe just
Date now = new Date();
Then, just let JPA worry about how to martial the current timestamp into your database table. If you really need to format your timestamp as shown, then worry about this in your Java code somewhere.

Date formatting issue for sql format 'YYYY-MM-DD HH24:MI:SS.FF' to java

In my sql query I have date formating as :
to_char(crtd_ts,'YYYY-MM-DD HH24:MI:SS.FF') crtd
and my database column stores the value as 2018-4-24.8.1. 30. 404577000
What is the way of doing the same thing in Java?
I tried this way, but I am getting an error.
private String formatDate(String refCrtdTs) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MMM-dd HH24:mm:ss.ff");
String dateInString = refCrtdTs;
try {
Date date = sdf.parse(dateInString);
} catch (ParseException e) {
e.printStackTrace();
}
return null;
}
I am trying to replace the above sql query with hibernate criteria. My hibernate entity for the column is defined as
#Column(name="REF_CRTD_TS",columnDefinition="timestamp")
private String refCrtdTs;
and the column type in Oracle is Timestamp.
So hibernate criteria returns me this value as String which I want to format now.
Try this,
yy-M-d H:m:s.F
And your database column stores the value should be "2018-4-24 8:1:30.114"
F is Day in year (example: Feb 1st => F = 32, 31 day in Jan + 1 day in Feb)
You have to match same patter as per your sql, just try the same pattern to get in Java
I think this will work, please comment if you required more info
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS aa");

Spring MongoDB - Finding Documents between two dates

I am somewhat new to Java and am trying to write a query which will return the documents stored in my mongodb between two dates. I think I am close to getting it correct but am having a hard time getting there. I am receiving the date ranges in the following format:
[2017-06-29, 2017-07-05]
The dates that i am comparing are stored in the database as follows:
yyyy-MM-dd'T'HH:mm:ss-SSSS
What i have so far..
public List<VehicleStatus> getReportingDateRange(List<String> dates) {
DateFormat inputFormat = new SimpleDateFormat("yyyy-MM-dd");
DateFormat outputFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss-SSSS");
Date startDate = outputFormat.parse(dates.get(0));
Date endDate = outputFormat.parse(dates.get(1));
Query query = new Query();
Criteria c = new Criteria().andOperator(Criteria.where("updateTime").gte(outputFormat.format(startDate)),
Criteria.where("updateTime").lte(outputFormat.format(endDate)));
query.addCriteria(c);
return this.mongoOperations.find(query, VehicleStatus.class);
}
I am receiving a parse Exception. I am really not sure where to go from here, any help is greatly appreciated. If you need any additional information please let me know.
Thank you!
You will need to parse the date into input format followed by formatting the date to output format.
Something like
String startDate = outputFormat.format(inputFormat.parse(dates[0]));
String endDate = outputFormat.format(inputFormat.parse(dates[0]));
Criteria c = new Criteria().andOperator(Criteria.where("updateTime").gte(star‌​tDate), Criteria.where("updateTime").lte(endDate));
You should try to save the date as date type and use below version.
Date startDate = inputFormat.parse(dates.get(0));
Date endDate = inputFormat .parse(dates.get(1));
Criteria c = new Criteria().andOperator(Criteria.where("updateTime").gte(star‌​tDate), Criteria.where("updateTime").lte(endDate));

Problems converting a UNIX_TIMESTAMP from a SQL query into a Date in java

I have a MySQL query made in this way:
SELECT AVG(REALPOWER) AS REALPOWER,
`OBJECTID`,
UNIX_TIMESTAMP(LASTUPDATE)/(30*60) AS LASTUPDATE
FROM POWER
GROUP BY UNIX_TIMESTAMP(LASTUPDATE)/(30*60),
OBJECTID
To get my rows grouped by 30 minutes intervals.
Then in Java i want to convert LASTUPDATE to a Date.
The problem is i cannot understand how to dwell with LASTUPDATE, which has values like these:
823945.7650000000, 823945.7705555550, 823945.7761111110
Even multiplying them to 1000 to get millis gives me no real value to get a date...
double last = Double.parseDouble(rs.getString("LASTUPDATE"));
Date date = new Date((long) last*1000L);
A Date object in Java is just a point in time. Using the 7 and earlier API, if you want to actually see a formatted date, then you will have to use something like SimpleDateFormat. Here is an example:
double last = Double.parseDouble(rs.getString("LASTUPDATE"));
Date date = new Date((long) last*1000L);
SimpleDateFormat sdf = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS", Locale.ENGLISH);
String dateFormatted = sdf.format(date);
System.out.println(dateFormatted);
Use floor() to convert the double value into an integer type. Something like:
floor(UNIX_TIMESTAMP(LASTUPDATE)/(30*60)) AS LASTUPDATE

Formatting timestamp in Java

I wish to produce a current timestamp in the format of yyyy-MM-dd HH:mm:ss. I have written up the following code, but it always gives me this format yyyy-MM-dd HH:mm:ss.x
How do you get rid of the .x part ?
DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String currentTime = df.format(new Date());
Timestamp timestamp = Timestamp.valueOf(currentTime);
I need to have a timestamp type for writing into mysql.
Probably you're looking at the String representation the Timestamp object gives in your database engine or its Java representation by printing it in the console using System.out.println or by another method. Note that which is really stored (in both Java side or in your database engine) is a number that represents the time since epoch (usually January 1st 1970) and the date you want/need to store.
You should not pay attention to the String format it is represented when you consume your Timestamp. This can be easily demostrated if you apply the same SimpleDateFormat to get a String representation of your timestamp object:
DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String currentTime = df.format(new Date());
Timestamp timestamp = Timestamp.valueOf(currentTime)
//will print without showing the .x part
String currentTimeFromTimestamp = df.format(currentTime);
Anyway, if you want the current time, just create the Timestamp directly from the result of new Date:
Timestamp timestamp = new Timestamp(new Date().getTime());
You can insert the timestamp as a String to the MySQL table. Your String representation in currentTime is sufficient.
The best way to write Timestamp or any data type in Java is to use PreparedStatement and an appropriate method
PreparedStatement ps = conn.prepareStatement("update t1 set c1=?");
ps.setTimestamp(1, new java.sql.Timestamp(new Date().getTime()));
ps.executeUpdate();

Categories

Resources