I am using Orientdb with Eclipse and the orientdb-client jar. I use the following statement to read out Messages:
List<ODocument> result = connection.command(
new OSQLSynchQuery<ODocument>(
"SELECT * FROM Message"))
.execute();
At first glance the results looks right, but then i realized that the time i read out from a DATTIME field is wrong.
When i run the query "select * from Message ", the locahost version gives me the following results (just a part of it):
When i run the java snippet from above, the results looks like :
For the formating i use a SimpleDateFormat:
DateFormat formatter = new SimpleDateFormat("HH:mm:ss a");
String time = formatter.format(each.field("Time"));
So why is the hour of the date different ( 2 hours) ? Could it be a Timezone issue?
It because database returns results in database's timezone.
You can see it from studio in section Db->configuration.
Command to update timezone looks like
alter database timezone GMT+6
Related
My program in Java connects to a Database (Oracle XE 11g) which contains many dates (date format of OracleXE is set to syyyy/mm/dd).
Doing a query in the database with negative dates (before Christ) works fine. When I do it in Java, they are all changed to AD (Anno Domini). How can I retrieve dates in Java respecting AD/BC?
My Java code here does the query to the DB and puts the result in a table.
try {
Object item=cbPD.getSelectedItem();
String dacercare=item.toString();
query = "SELECT DISTINCT PD.Titolo,PD.Inizio,(Select E.nome From Evento E WHERE PD.Inizio_Evento=E.CODE),
PD.Fine, (Select E.nome From Evento E WHERE PD.Fine_Evento=E.CODE ) FROM Periododelimitato PD WHERE PD.Titolo=?";
PreparedStatement stAccess = Login.connessione.prepareStatement(query, ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
stAccess.setString(1,dacercare);
rset = stAccess.executeQuery();
j = modelPD.getRowCount();
for (i=0; i<j; i++) modelPD.removeRow(0);
Date data;
while (rset.next()) {
data = rset.getDate(2);
modelPD.addRow(new Object[]{rset.getString(1),data, rset.getString(3), rset.getString(4), rset.getString(5)});
}
}
Here an Example using a specific Query:
try {
query = "SELECT PD.Inizio FROM PeriodoDelimitato PD WHERE PD.CodP=?";
String dacercare="8"; //look for record with this specific Primary key
PreparedStatement stAccess = Login.connessione.prepareStatement(query,
ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
stAccess.setString(1, dacercare);
rset = stAccess.executeQuery();
while(rset.next()) {
Date dateBC = rset.getDate(1);
modelPD.addRow(new Object[]{null, dateBC, null, null, null});
}
Output in Java is:
0509-01-01
Output using the same query (substituing ? with the primary key specified) in Sql developer:
-0509/01/01
Note on the query: the column selected in this example is in Oracle a DATE type.
Adding information: DBMS is Oracle (XE 11g), DB has been built on IDE (SQL developer). The program is written in Java through Netbeans 8.2. I connect to the database in Netbeans adding the Library "ojdbc6.jar".
First, it’s not immediately clear how you should handle historic and not least prehistoric dates and how you should expect them to behave. It’s not something I know, but I doubt that any calendar in common use today was used in the 6th century BCE (before the common era, “BC”). Maybe you were already aware, I just wanted to mention it for anyone else reading this answer.
With thanks to Basil Bourque’s (now deleted) answer, what you have observed seems to be the intended behaviour with java.sql.Date. I tried printing dates from year 2 CE (common era, “AD”) and then year 2 BCE and compared. First 2 CE:
LocalDate ld = LocalDate.of(2, 1, 1);
java.sql.Date sqlDate = java.sql.Date.valueOf(ld);
System.out.println("java.sql.Date " + sqlDate + " millis " + sqlDate.getTime());
java.sql.Date 0002-01-01 millis -62104237200000
This is as expected. For 2 BCE we need to supply -1 to LocalDate since 0 means 1 BCE, and -1 means 2 BCE. Insert LocalDate.of(-1, 1, 1) in the above code, and the output is
java.sql.Date 0002-01-01 millis -62198931600000
We note that the date is printed the same. 0002 is hardly downright incorrect, but it doesn’t tell us whether it’s year 2 CE or BCE. I believe that this explains the behaviour you observed. Next we note that the millisecond values are different, so the dates are different as they should be. The diffirence is 94694400000 milliseconds, which equals 1096 days or 3 years if one of them is a leap year. The leap year may surprise, but otherwise I think it’s correct.
There is something fishy, though. When I converted the sql date back into a LocalDate, the era was lost, I always got a date in the common era. Since you don’t need this conversion, you probably don’t need to care.
I believe the good solution will be to drop the outdated Date class completely and use the modern LocalDate throughout. You should be aware that this follows the so-called proleptic Gregorian calendar, which may not always give the exact same dates as Date. Also this requires JDBC 4.2 compliant driver, so your ojdbc6.jar won’t do. Even though this may mean you’re prevented, I am letting the suggestion stand for anyone else reading along. I have not tested, but I think the following should work:
LocalDate dateBC = rset.getObject(1, LocalDate.class);
A solution using the old Date type to query SQL dates BC and AC that is working is to declare into my class a SimpleDataFormat with the format specified below
public SimpleDateFormat sdf= new SimpleDateFormat("yyyy-MM-dd G");
Then I declared a Date dataOUT invoking the format method of SimpleDataFormat giving as input the Date BC queried from the Database
dataOUT=sdf.format(rset.getDate(2));
Thank you all for the time dedicated to my question!
Hi all i have a problem in a insert query.
I get datetime from java with:
SimpleDateFormat sdfDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date now = new Date();
String strDate = sdfDate.format(now);
p.s: I have try a sysout on strDate and it is correct.
I read a question, like that, where to enter in MySQL datetime must make a query like this:
INSERT INTO tracks (in) VALUES (STR_TO_DATE( ? ,'%Y-%m-%d %r'))
Where '?' is the string containing the date, but it don' t work.
Can anyone help me?
UPDATE: MySQL Server 5.7
You have use current time. So you can do it simply with NOW().
INSERT INTO tracks (`in`) VALUES (NOW())
OR
You can do this way
java.sql.Timestamp now = new java.sql.Timestamp(new java.util.Date().getTime());
PrepStmt.setTimestamp(1, now);
I have found the problem.
The name "in" for the DateTime field is not accepted.
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'in, session) VALUES (1, NOW(), "abc")' at line 1.
'in, session)
I have try to rename it in "indate" and the query:
INSERT INTO tracks (fk_utenza, indate, session) VALUES (1, NOW(), "abc");
works well!
I have to compare an EQUAL comparison between dates from UI and DB. Its working with below code
ExtJs Code :-
xtype: 'datefield'
,fieldLabel:'By Date'
,name: 'byDate'
,format: 'd-m-Y'
,flex:1
and Code in Java is :-
query.addCriteria(Criteria.where("bookingtime").regex(byDate, "i"));
The format d-m-Y gives me date in format 27-11-2016 or 15-10-2016. If the date in DB is as same as in date from UI ,like 27-11-2016 etc, this works like a charm.
But the problems arises when I select date in UI as 07-01-2016 which becomes 7-1-2016 in java. Since date in DB is in format 07-01-2016 and it fails the match and I get nothing.
Could you please help.
I make an application based on hibernate,
I just wanna ask,
How to parse this "31/10/13" to Oracle date in Java,
before this, I've try this method
SimpleDateFormat sdf1 = new SimpleDateFormat("dd/MM/yyyy");
Date log_date = sdf1.parse(tgl1);
it works, but when I try to make a simple query to search data like this
select * from coreservice where log_date='31-OCT-13';
but I got no data found in result....
Any help will be pleasure :)
Use oracle to_date functionin your query as follows:
select * from coreservice where log_date = to_date('31-OCT-2013','dd/mon/yyyy');
I'm trying to retrieve a list of events from a google calendar, using the Java api (jar version v3-rev9-1.7.0-beta)
This code works fine
Events e = service.events().list("primary").
setMaxResults(3).
execute();
where service is a Calendar object.
However, if I add a setTimeMin or setTimeMax parameter, like this
Date now = new java.util.Date();
Events e = service.events().list("primary").
setTimeMin(new DateTime(now)).
setMaxResults(3).
execute();
it returns a failure message, "Bad Request".
(note that as of this version, the setTime functions take a google DateTime object. I've also tried with the previous version of the jar, which takes a string, but received the same message).
So I was just wondering if anyone has successfully used these functions - perhaps they're not supposed to be called in this manner? Is there a way to get more detail back on the error?
Thanks :)
DateTime startTime = new DateTime(new Date(), TimeZone.getDefault());
Sorts the problem
I also encountered this. It seems the format of the DateTime.toString() or DateTime.toStringRfc3339() methods are incorrect as input to setTimeMin().
The DateTime.toString() format is:
2012-07-04T21:02:16.590
yyyy-MM-dd'T'HH:mm:ss.SSS (SimpleDateFormat notation)
The format which it expects seems to be close to xsd:datetime format (whatever that is):
2012-07-04T21:02:16Z (zulu, gmt)
2012-07-04T21:02:16-07:00 (mst, -7h)
2012-07-04T21:02:16-0700 (it also works without the colon in the timezone)
yyyy-MM-dd'T'HH:mm:ssZ (SimpleDateFormat)
Formatting can be done with a SimpleDateFormat:
SimpleDateFormat FMT_TIME=new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
String fromTimeStr=FMT_TIME.format(new Date());
Events evts = client.events().list(cal.getUid()).setTimeMin(fromTimeStr)
.execute();
Now, since I'm using the older API, I'm not sure how this would be done if the only method is setTimeMin(DateTime), but this should get you closer.
The Google documentation or source should mention this somewhere.