java simple date pattern TO oracle sql date pattern - java

I have following web application:
Users can enter java simple date format patterns and a date (of course matching to the java simple date format pattern) and I want to store these date in an oracle database.
Therefore I need to translate the java simple date format pattern into the oracle pattern.
E.g:
"dd-MM-yyyy HH:mm:ss" into "DD-MM-YYYY HH24:MI:SS"
"dd-MM-yy HH:mm:ss" into "DD-MM-YY HH24:MI:SS"
"dd-MM-yy HH:mm" into "DD-MM-YY HH24:MI"
and so on.
Instead of the following code just having one SimpleDateFormat I would like to have all or at least a big bunch of SimpleDateFormatPatterns translated into Oracle pattern:
SimpleDateFormat sFormat = new SimpleDateFormat( "dd-MM-yyyy HH:mm:ss");
String sqlSnippet = "TO_DATE('" + sFormat.format(date) + "','DD-MM-YYYY HH24:MI:SS')";
Is there a library or maybe just a mapping list to do this?
Thanks.
Edit:
I need to build the SQL by hand as the user defines the criteria, compare operators and joins in the user interface.
In the end I have something like this
AND col2 > TO_DATE('26-09-2012','DD-MM-YYYY')

Therefore I need to translate the java simple date format pattern into the oracle pattern
No, you don't. You should instead use a PreparedStatement, and call setDate or setTimestamp on it to specify the value you're interested in.
Avoid string conversions unless they're fundamentally part of what you're trying to do (e.g. displaying a date/time in a UI). For simply transferring information from your app to your database or vice versa, you should reduce the number of conversions required as far as possible.

The Answer by Jon Skeet is correct but is now outdated in referring to some legacy classes. The java.sql.Date and java.sql.Timestamp and related classes are now supplanted by the java.time classes, LocalDate and Instant respectively. But your Question demands the LocalDateTime class.
Smart objects, not dumb strings
You objects to represent your date-time values. As of JDBC 4.2 and later, you can directly exchange java.time objects with your database.
Your inputs lack any indicator of time zone or offset-from-UTC. So parse in Java as a LocalDateTime for storage in a column of a type similar to SQL-standard TIMESTAMP WITHOUT TIME ZONE.
DateTimeFormatter f1 = DateTimeFormatter.ofPattern( "dd-MM-uuuu HH:mm:ss" ) ;
DateTimeFormatter f2 = DateTimeFormatter.ofPattern( "dd-MM-uu HH:mm:ss" ) ;
DateTimeFormatter f3 = DateTimeFormatter.ofPattern( "dd-MM-uu HH:mm" ) ;
Choose a formatter by length of the input string.
LocalDateTime ldt = LocalDateTime.parse( myInputString , f2 ) ;
I need to build the SQL by hand as the user defines the criteria, compare operators and joins in the user interface. In the end I have something like this
String sqlSnippet = "TO_DATE('" + sFormat.format(date) + "','DD-MM-YYYY HH24:MI:SS')";
No, do not embed your date-time value as text in a String of SQL. Instead, use a PreparedStatement with ? placeholders replaced with your LocalDateTime object.
String sql = "SELECT when FROM tbl WHERE when > ? ;" ;
Pass the object to be slipped into that placeholder at runtime.
myPreparedStatement.setObject( … , ldt ) ;
Retrieval:
LocalDateTime ldt = myResultSet.getObject( … ; LocalDateTime.class ) ;
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.
Where to obtain the java.time classes?
Java SE 8, Java SE 9, and later
Built-in.
Part of the standard Java API with a bundled implementation.
Java 9 adds some minor features and fixes.
Java SE 6 and Java SE 7
Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
Later versions of Android bundle implementations of the java.time classes.
For earlier Android (<26), the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

Related

Parse timestamp string to Java.sql.timestamp [duplicate]

This question already has answers here:
Converting ISO 8601-compliant String to java.util.Date
(31 answers)
Java: Convert String to TimeStamp
(11 answers)
Closed 3 years ago.
I have the following timestamp in String format
2019-04-06T00:43:21+00:00
2019-04-04T21:24:33+00:00
2019-04-04T21:02:16+00:00
How can I parse the timestamp strings above to Java.sql.timestamp?
Use DateFormat to parse your String.
try{
String x="2019-04-04T21:24:33+00:00";
DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ssX");
Date date = (Date) df.parse(x);
java.sql.Timestamp timeStamp = new java.sql.Timestamp(date.getTime());
}catch(ParseException pe){
pe.printStackTrace();
}
As mentioned by others in comments, there is a more updated way to do this.
String time="2019-04-04T21:02:16+00:00";
OffsetDateTime odt=OffsetDateTime.parse(time,DateTimeFormatter.ISO_OFFSET_DATE_TIME);
java.sql.Timestamp timestamp=new java.sql.Timestamp(odt.toEpochSecond()*1000);
tl;dr
Timestamp // Avoid this terrible legacy class if possible. Represents a moment in UTC.
.from( // Convert from modern `Instant` to legacy `Timestamp`. No data loss, as both resolve to nanoseconds.
OffsetDateTime // Modern way to represent a moment with an offset-from-UTC (hours, minutes, and seconds).
.parse( "2019-04-06T00:43:21+00:00" ) // Parse standard ISO 8601 strings. Returns a `java.time.OffsetDateTime` object.
.toInstant() // Extract an `Instant` from the `OffsetDateTime`, thereby adjusting to UTC (an offset of zero).
) // Returns a `Timestamp` object, if needed to interoperate with old code not yet updated to *java.time*.
Even better, skip the terrible Timestamp class entirely.
myPreparedStatement.setObject( // As of JDBC 4.2 and later, exchange *java.time* objects with your database.
1 , // Specify the nth placeholder in your SQL statement.
OffsetDateTime.parse( "2019-04-06T00:43:21+00:00" ) // Parse an ISO 8601 compliant string as a `OffsetDateTime` object, a moment with an offset-from-UTC. Pass to the database via the `setObject` call.
)
OffsetDateTime
Your input strings indicate an offset-from-UTC (a number of hours-minutes-seconds), that part at the end.
Your input strings are in standard ISO 8601 format. The java.time classes use these formats by default in parsing/generating strings. So no need to specify a formatting pattern.
OffsetDateTime odt = OffsetDateTime.parse( "2019-04-06T00:43:21+00:00" ) ;
java.sql.Timestamp
Never use java.util.Timestamp. That terrible class was supplanted years ago by the modern java.time classes.
If you must have a Timestamp object to interoperate with old code not yet updated to java.time, convert by calling new methods added to the old classes. Extract a Instant from the OffsetDateTime (thereby adjusting from any offset to an offset of zero, for UTC itself). Pass the Instant object to Timestamp.from.
java.sql.Timestamp ts = Timestamp.from( odt.toInstant() ) ;
JDBC 4.2
As of JDBC 4.2, we can exchange java.time objects with the database.
myPreparedStatement.setObject( … , odt ) ;
Retrieval.
OffsetDateTime odt = myResultSet.getObject( … , OffsetDateTime.class ) ;
All this has been covered many many times already on Stack Overflow. So search for more info. And in the future, search thoroughly before posting.
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.
Where to obtain the java.time classes?
Java SE 8, Java SE 9, Java SE 10, Java SE 11, and later - Part of the standard Java API with a bundled implementation.
Java 9 adds some minor features and fixes.
Java SE 6 and Java SE 7
Most of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
Later versions of Android bundle implementations of the java.time classes.
For earlier Android (<26), the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

How to properly format Date in yyyy-mm-dd?

I have a column in my table of Date type in MYSQL and inserting the date format of 25-March-2019 hh:mm:ss returns an error telling me incorrect data value.
So I have my code written like this:
String startdt=request.getParameter("startdate");
String enddate=request.getParameter("enddate");
SimpleDateFormat dateFormat=new SimpleDateFormat("yyyy-MM-dd");
Date Startdate=dateFormat.parse(startdt);
Date Enddate=dateFormat.parse(enddate);
And I am passing Startdate and Enddate to a function that inserts into my table column.
Is there a way I can have Startdate and Enddate above just return in yyyy-mm-dd without the time so I can insert to my db without error?
tl;dr
myPreparedStatement
.setObject(
LocalDate.parse( "2019-01-23" )
) ;
DATE in MySQL is date-only
The DATE type in MySQL is a date-only value, without time-of-day and without time zone.
Excerpting from MySQL 8.0 documentation:
The DATE type is used for values with a date part but no time part. MySQL retrieves and displays DATE values in 'YYYY-MM-DD' format. The supported range is '1000-01-01' to '9999-12-31'.
Use a date-only type in Java for data coming from a date-only type in your database. The java.util.Date class you are trying to use is not a date, it is a moment in UTC, a date with time-of-day and offset-from-UTC of zero, all tracked as a count of milliseconds from the first moment of 1970 in UTC. The misnaming of that class is only the first of many poor design choices made by those programmers. Move on to java.time classes instead. Stop using Date.
MM = month number, not name
Your format of "yyyy-MM-dd" is for a numeric month, not the string of month name shown in your example value of 25-March-2019.
Avoid legacy date-time classes
The SimpleDateFormat and Date classes are terrible, a wretched mess of bad design. They were supplanted years ago with the adoption of JSR 310, implemented in the java.time classes.
Smart objects, not dumb strings
Exchange objects with your database where possible, not text.
As of JDBC 4.2, we can directly exchanged java.time objects with the database. For a date-only value, as with SQL-standard DATE type, use the java.time.LocalDate class.
Apparently, your text inputs for date values is YYYY-MM-DD which is standard ISO 8601 format. The java.time classes use ISO 8601 formats by default. So no need to specify a formatting pattern.
LocalDate localDate = LocalDate.parse( "2019-01-23" ) ;
myPreparedStatement.setObject( … , localDate ) ;
Retrieval.
LocalDate localDate = myResultSet.getObject( … , LocalDate.class ) ;
localDate.toString(): 2019-01-23
If you want to produce a string representing the value of that LocalDate object in a different textual format, use the DateTimeFormatter class. Search Stack Overflow for more info as it, like the rest of your Question, has been covered many times already on Stack Overflow. Do search Stack Overflow before posting.
Tip: Generally best to use a PreparedStatement in your JDBC work. One major benefit is thwarting SQL Injection security attacks.
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.
Where to obtain the java.time classes?
Java SE 8, Java SE 9, Java SE 10, Java SE 11, and later - Part of the standard Java API with a bundled implementation.
Java 9 adds some minor features and fixes.
Java SE 6 and Java SE 7
Most of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
Later versions of Android bundle implementations of the java.time classes.
For earlier Android (<26), the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.
Java 7 and ThreeTen Backport
DateTimeFormatter formatter
= DateTimeFormatter.ofPattern("d-MMMM-uuuu HH:mm:ss", Locale.ENGLISH);
String dateFromHtmlForm = "25-March-2019 22:43:55";
LocalDateTime dateTime = LocalDateTime.parse(dateFromHtmlForm, formatter);
// We are discarding the time of day and only saving the date
java.sql.Date dateToSave = DateTimeUtils.toSqlDate(dateTime.toLocalDate());
String insertSql = "insert into your_table (your_date_column) values (?);";
try (PreparedStatement insertStatement
= yourDatabaseConnection.prepareStatement(insertSql)) {
insertStatement.setDate(1, dateToSave);
int rowsInserted = insertStatement.executeUpdate();
}
As has already been said, pass date objects to MySQL, not strings. In Java 8 and later these would have been LocalDate objects, but in Java 7 we will need to make do with the poorly designed java.sql.Date class. It’s still better than strings. And the conversion from LocalDate is straightforward.
On Java 7 we can use java.time through the backport, ThreeTen Backport (ThreeTen for JSR-310). My imports are:
import org.threeten.bp.DateTimeUtils;
import org.threeten.bp.LocalDateTime;
import org.threeten.bp.format.DateTimeFormatter;
Why would we want to use an external library for this? There are pros and cons, of course. Advantages include:
java.time is so much nicer to work with than the old-fashoined Date and SimpleDateFormat and gives clearer code.
It’s future-proof: once you move to Java 8 or later, all you need to do is change your import statements (and discard the library and retest).
Links
Oracle tutorial: Date Time explaining how to use java.time.
Java Specification Request (JSR) 310, where java.time was first described.
ThreeTen Backport project, the backport of java.time to Java 6 and 7.
ThreeTenABP, Android edition of ThreeTen Backport
Question: How to use ThreeTenABP in Android Project, with a very thorough explanation.

Unmarshalling JSON sql Date fields from servlet, mine gets date wrong?

I am using JSON to get data from an HttpServlet for data object class definitions that are shared between the servlet and a java client. If I print out the response from the api call I can see that the instance variable is correct. Then when I map it using Jackson object mapper and look at the instance the value is wrong, always by one day lower then the date in the response and in the database.
The response looks like:
[{"coveragePK":3,"agentPK":2,"serviceCoveragePK":12,
"coverageDate":"2018-02-27","duration":10,"remainder":1,
"startTime":"07:30:00","query":""},
{"coveragePK":4,"agentPK":2,"serviceCoveragePK":13,
"coverageDate":"2018-02-27","duration":8,"remainder":2,
"startTime":"10:00:00","query":""}]
and after I map it I get:
Date: 2018-02-26 which is printed with
java.sql.Date date = coverages[i].getCoverageDate();
System.out.println("Date: " + date.toString());
If I convert the sql.Date to a LocalDate the result is the same as one would expect.
I use the following to write the json where coverages is an ArrayList.
ObjectMapper mapper = new ObjectMapper();
String psWindows = mapper.writeValueAsString(coverages);
PrintWriter out = httpServletResponse.getWriter();
out.append(psWindows);
And I read the JSON with
ObjectMapper mapper = new ObjectMapper();
CoverageDO[] coverage = mapper.readValue(foo, CoverageDO[].class);
I suspect the problem is in your timezone.
java.sql.Date stores the date like a timestamp (time since January 1, 1970, 00:00:00 GMT), but when it gets converted to java.util.Date. Try to use SimpleDateFormat to check the real date.
new SimpleDateFormat("yyyy-MM-dd HH:mm:ss Z").parse(date);
tl;dr
LocalDate.parse( "2018-02-27" )
java.time
The java.sql.Date class is part of the troublesome old date-time classes that are now legacy, supplanted by the java.time classes.
LocalDate ld = LocalDate.parse( "2018-02-27" ) ;
LocalTime lt = LocalTime.parse( "10:00:00" ) ;
Generate a string representing that date’s value using standard ISO 8601 format by calling toString.
String output = ld.toString() ;
2018-02-27
Put those two together.
LocalDateTime ldt = LocalDateTime.of( ld , lt ) ;
ldt.toString(): 2018-02-27T10:00:00
A LocalDateTime lacks any concept of time zone or offset-from-UTC. As such, a LocalDateTime does not represent a moment, is not a point on the timeline. It represents a vague idea of potential moments along a range of about 26-27 hours.
To determine an actual moment, place it into the context of a time zone (or offset) if you are absolutely certain such a zone/offset was intended.
If I convert the sql.Date to a LocalDate
Don’t. No need to ever use java.sql.Date again. Just use LocalDate.
If you must inter-operate with old code not yet updated to java.time classes, then call new conversion methods added to the old classes.
LocalDate ld = myJavaSqlDate.toLocalDate() ; // From legacy class to modern class.
java.sql.Date myJavaSqlDate = java.sql.Date.valueOf( ld ) ; // Vice-versa. From modern class to legacy class.
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.
Where to obtain the java.time classes?
Java SE 8, Java SE 9, and later
Built-in.
Part of the standard Java API with a bundled implementation.
Java 9 adds some minor features and fixes.
Java SE 6 and Java SE 7
Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
Later versions of Android bundle implementations of the java.time classes.
For earlier Android, the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

Java SimpleDateFormat doesn't Give Constant Result

I need to format the Java Date object into a String like yyyyMMdd (round to day). For e.g, 20180129. I have the following implementation:
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
sdf.format(roundedDate);
The code works most the time, but sometimes it'll generate results like 2018129, which is not what I want. So I'll have both 20180129 and 2018129 in my database.
The app consumes messages from a MQ and ummarshalls the timestamp in the message into a Java Date object. And it formats the date into a the above String.
The issue is that I cannot reproduce the issue in debug mode. It always produces the expected results in the debugger. But after I ran it on a server (in Docker) for some time, I see such corrupted data.
I wonder why the SimpleDateFormat could have such undetermined behavior given a valid Date object? Any idea will be appreciated.
SimpleDateFormat is not thread-safe, see this excellent article.
java.time.format.DateTimeFormatter is the modern thread-safe implementation of this functionality in the core Java.
tl;dr
Use the thread-safe java.time classes instead.
Specifically, use LocalDate and DateTimeFormatter.BASIC_ISO_DATE.
LocalDate.parse(
"2018129" ,
DateTimeFormatter.BASIC_ISO_DATE
)
2018-01-29
LocalDate.now()
.format( DateTimeFormatter.BASIC_ISO_DATE )
20180129
Thread-safety
You do not provide enough information to diagnose your problem. I would guess either:
You are using those legacy date-time objects across threads, and they were not designed to be thread-safe. Instead use the java.time classes which are designed to be thread-safe by design via immutable objects pattern.
Something is going wrong during whatever you are doing in this mysterious “date rounding” which you mention but neglect to explain.
Wrong data type
timestamp in the message into a Java Date object.
You are putting a date-only value into a date-with-time-of-day type. Square peg, round hole.
Instead, use a date-only type for a date-only value: LocalDate.
ISO 8601
Your desired format YYYYMMDD happens to be defined in the ISO 8601 standard, as the “basic” variant where the use of delimiters is minimized.
Java provides a DateTimeFormatter object for this purpose: DateTimeFormatter.BASIC_ISO_DATE. So no need to define a formatting pattern.
String input = "2018129" ;
LocalDate ld = LocalDate.parse( input , DateTimeFormatter.BASIC_ISO_DATE ) ;
To generate such a string, use the same formatter.
LocalDate today = LocalDate.now( ZoneId.of( "Africa/Tunis" ) ) ;
String output = today.format( DateTimeFormatter.BASIC_ISO_DATE ) ;
By the way, I recommend using the full-length versions of ISO 8601 formats rather than the compact “basic” variants. The few bytes saved are not worth giving up the readability and reduced ambiguity, in my experience. Plus, the java.time classes use the full-length ISO 8601 formats by default when parsing/generating String objects, so you can dispense with DateTimeFormatter objects entirely.
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.
Where to obtain the java.time classes?
Java SE 8, Java SE 9, Java SE 10, and later
Built-in.
Part of the standard Java API with a bundled implementation.
Java 9 adds some minor features and fixes.
Java SE 6 and Java SE 7
Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
Later versions of Android bundle implementations of the java.time classes.
For earlier Android (<26), the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

Is Oracle db able to compare timestamps with different timezones?

I'd like to know if Oracle is able to compare dates with different Timezones, as in:
12/26/2016 3:58:16.491476 AM -06:00 > 12/26/2016 3:58:16.491476 AM +05:00
Btw, I'm using JPA to do this comparison, the idea would be to look for all the rows created an hour ago.
I found that I might be able to use the After keyword to look for it (i.e. findMeasureDateAfter)
Very easy to check in Oracle. The answer is YES. Please note, in the illustration below the output shows timestamps using my session's NLS settings (I didn't care to change them).
with
inputs ( ts1, ts2 ) as (
select to_timestamp_tz('12/26/2016 3:58:16.491476 AM -06:00',
'mm/dd/yyyy hh:mi:ss.ff AM TZH:TZM'),
to_timestamp_tz('12/26/2016 3:58:16.491476 AM +05:00',
'mm/dd/yyyy hh:mi:ss.ff AM TZH:TZM') from dual
)
select ts1, ts2, case when ts1 > ts2 then 'ts1 > ts2'
when ts1 = ts2 then 'ts1 = ts2'
when ts1 < ts2 then 'ts1 < ts2'
end as comparison,
ts1 - ts2 as difference
from inputs
;
TS1 TS2 COMPARISON DIFFERENCE
----------------------------- ----------------------------- ---------- -------------------
26-DEC-16 03.58.16.491 AM -06 26-DEC-16 03.58.16.491 AM +05 ts1 > ts2 +00 11:00:00.000000
If you are pulling the data from an Oracle table based on a predicate like this, it is much better to do that work in the database - so how this would be done in Java is irrelevant. (You certainly don't want to fetch all the rows, only to ignore most of them after you check the timestamp in Java.) Of course, if you need "the last hour" you would compare against systimestamp - 1/24.
ISO 8601
First, if those inputs are actually strings as presented in the Question, use standard ISO 8601 formats instead if at all possible. The standard formats are intuitive to humans and easier to parse by computers. Indeed, the java.time classes use ISO 8601 formats by default when parsing/generating strings.
java.time
While I do not know about the the query in Oracle (I'm a Postgres man myself), I can show how to form the query more on the Java side.
Ideally we would parse that input string as a OffsetDateTime as it lacks an indication of time zone, only has offset-from-UTC. A zone is an offset plus a set of rules for handling anomalies such as Daylight Saving Time (DST). A time zone is named in format of continent/region such as America/Montreal.
Unfortunately, the java.time implementation in Java 8 has some bugs around parsing offset-from-UTC in the DateTimeFormatter class. So until Java 9, here is a bit of hack code to parse as a ZonedDateTime and convert to the more appropriate OffsetDateTime.
String input = "12/26/2016 3:58:16.491476 AM -06:00";
DateTimeFormatter f = DateTimeFormatter.ofPattern ( "MM/dd/uuuu h:m:s.SSSSSS a z" , Locale.ENGLISH );
OffsetDateTime odt = ZonedDateTime.parse ( input , f ).toOffsetDateTime ();
odt.toString(): 2016-12-26T03:58:16.491476-06:00
Repeat for your ending moment.
If your JDBC driver supports JDBC 4.2 or later, you may be able to pass these java.time types directly via PreparedStatement::setObject.
If not, convert to java.sql types. To convert, look to new methods added to the old classes. The from method takes an Instant which is a moment on the timeline in UTC. You can think of an Instant as a OffsetDateTime stripped of its offset. Call OffsetDateTime::toInstant to extract an Instant.
java.sql.Timestamp ts = java.sql.Timestamp.from( odt.toInstant() ) ;
Do this for both your beginning and ending moments. Pass these java.sql.Timestamp objects to your PreparedStatement.
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
Where to obtain the java.time classes?
Java SE 8 and SE 9 and later
Built-in.
Part of the standard Java API with a bundled implementation.
Java 9 adds some minor features and fixes.
Java SE 6 and SE 7
Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
The ThreeTenABP project adapts ThreeTen-Backport (mentioned above) for Android specifically.
See How to use ThreeTenABP….
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

Categories