Add some hours/mins to current datetime and get the future datetime - java

I need to get the get the future timestamp value for a particular time. I will have to add a string value to the current datetime timestamp and get the future timestamp value.
I am fetching current timestamp as below:
Timestamp timestamp = new Timestamp(System.currentTimeMillis());
I have a string value as "02:00:00", so basically I need to add 2 hrs to this time and get the future timestamp value that needs to be inserted.
For example if current timestamp is: 2019-04-29 16:59:21.43
and String is "02:00:00".
I need output as 2019-04-29 18:59:21.43.
Can someone please help

You can do something like this
Instant now = Instant.now();
Duration diff = Duration.between(
LocalTime.MIN,
LocalTime.parse("02:00:00")
);
Instant res = now.plus(diff);
System.out.println("res = " + Timestamp.from(res));

You can use the MySQL function TIMESTAMP to add a given time string to your timestamp value:
TIMESTAMP(expr), TIMESTAMP(expr1,expr2)
With a single argument, this function returns the date or datetime
expression expr as a datetime value. With two arguments, it adds the
time expression expr2 to the date or datetime expression expr1 and
returns the result as a datetime value.
mysql> SELECT TIMESTAMP('2003-12-31 12:00:00','12:00:00');
-> '2004-01-01 00:00:00'
Reference

tl;dr
Insert a moment two hours from now.
myPreparedStatement // Use a `PreparedStatement` to exchange data with your database, to avoid SQL-injection risk. Use JDBC 4.2 or later for *java.time* support.
.setObject( // Fill a placeholder `?` in your SQL statement.
… , // Specify which placeholder.
OffsetDateTime // Use `OffsetDateTime` to specify a moment in JDBC 4.2. Optionally, your JDBC might support `Instant` or `ZonedDateTime` types, while support for `OffsetDateTime` is required.
.now( // Capture the current moment.
ZoneOffset.UTC // Set the offset-from-UTC to zero. We do not need to account for any time zone in this particular business scenario.
) // Returns an `OffsetDateTime` object.
.plus( // Adds a span-of-time to the moment held in the `OffsetDateTime` object.
Duration.parse( "PT2H" ) // Specify the span-of-time using standard ISO 8601 format for a duration.
) // Per Immutable Objects pattern, returns a new `OffsetDateTime` rather than changing ("mutating") the original.
)
Details
I have a string value as "02:00:00", so basically I need to add 2 hrs to this time and get the future timestamp value that needs to be inserted
That is a poor way to communicate a span-of-time unattached to the timeline.
The standard way is PnYnMnDTnHnMnS where the P marks the beginning, and the T separates the years-months-days from the hours-minutes-seconds. So 2 hours is PT2H.
To parse such a string, use Duration class for hours-minutes-seconds (or Period for years-months-days).
String input = "PT2H" ;
Duration d = Duration.parse( input ) ;
You can generate such a string.
String output = Duration.ofHours( 2 ).toString() ; // Yields "PT2H" string.
Capture the current moment in UTC.
OffsetDateTime odt = OffsetDateTime.now( ZoneOffset.UTC ) ;
Add a duration of two hours using standard ISO 8601 notation.
Duration d = Duration.parse( "PT2H" ) ;
ZonedDateTime odtLater = odt.plus( d ) ; // Add 2 hours to the current moment.
Submit that to your database using JDBC 4.2 or later.
myPreparedStatement.setObject( … , odtLater ) ;
Retrieval.
OffsetDateTime odt = myResultSet.getObject( … , OffsetDateTime.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.
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.

I like to consider my timestamps as unsigned ints. It becomes quite silple to modify them : in your case, try to get an uint representation and just add 2 * 3600 * 1000 to the timestamp, then format it tonthe output you want.

Related

How to update a Timestamp field in MySql from a Java PreparedStatement?

My index.html has an <input type="datetime-local"> field and I need to update a MySql database with whatever value the user selects. My database field is currently a Timestamp. How can I create an update statement that allows me to update the database with this datetime-local value? I've tried many options and my current attempt is shown below; however, this does not work. I am doing this all in Java.
String updateStatement = "UPDATE cars SET reservation = ? WHERE uniqueID = ?";
pStmt = con.prepareStatement(updateStatement);
pStmt.setTimestamp(1, reservation);
pStmt.setTimestamp(2, someUniqueId);
tl;dr
To answer your specific code question (but this is the wrong way to handle appointments/reservations):
myPreparedStatement
.setObject(
1 ,
ZonedDateTime
.of
(
LocalDate.of( 2021 , Month.JANUARY , 23 ) ,
LocalTime.of( 15 , 30 ) ,
ZoneId.of( "Africa/Tunis" )
)
.toInstant()
.atOffset( ZoneOffset.UTC )
)
;
java.time
The TIMESTAMP type in MySQL is for tracking a moment, a specific point on the timeline, as seen from an offset of zero hours-minutes-seconds from UTC, resolving to microseconds. This maps to TIMESTAMP WITH TIME ZONE in standard SQL.
The appropriate match in Java would be java.time.Instant. This class also represents a moment as seen in UTC, but with finer resolution of nanoseconds.
Unfortunately, the JDBC 4.2 specification requires support for only one of the three types that track a moment: OffsetDateTime. Both Instant and ZonedDateTime are optional in JDBC 4.2. So your particular JDBC driver may or may not support Instant. This design decision by the JDBC team baffles me. Converting between Instant and OffsetDateTime is utterly simple, and should have been required by JDBC spec.
I am guessing you are letting users pick a date and a time-of-day within a particular time zone. But I'm not sure, as your neglected to detail your inputs.
LocalDate localDate = LocalDate.of( 2021 , Month.JANUARY , 23 ) ;
LocalTime localTime = LocalTime.of( 15 , 30 ) ;
ZoneId zoneId = ZoneId.of( "America/Edmonton" ) ;
ZonedDateTime zdt = ZonedDateTime.of( localDate, localTime , zoneId ) ;
To store in the database, let's adjust from a time zone to UTC (an offset of zero). Convert from ZonedDateTime to Instant, and then to OffsetDateTime with an offset of zero hours-minutes-seconds represented by the constant ZoneOffset.UTC.
OffsetDateTime odt = zdt.toInstant().atOffset( ZoneOffset.UTC ) ; // Use `OffsetDateTime` rather than `Instant` for maximum compatibility across JDBC 4.2 drivers.
Do not call PreparedStatement#setTimestamp. That method is now legacy, for the terrible java.sql.Timestamp class. Never use date-time classes outside the java.time package. Those legacy classes were supplanted years ago by the modern java.time classes defined in JSR 310.
Call PreparedStatement#setObject. The JDBC team has yet to define specific set… methods for the various java.time classes. Again, a design decision which baffles me. However, we can exchange the java.time objects using setObject/getObject.
myPreparedStatement.setObject( … , odt ) ;
Retrieval.
OffsetDateTime odt = myResultSet.getObject( … , OffsetDateTime.class ) ;
Tracking appointments
By the way, you mentioned the business problem is making restaurant reservations in the future. For this work, you are taking the wrong approach.
Such future appointments are not tracked as moments, are not specific points on the timeline. If politicians were to change the offset used by that time zone, your customers expect a restaurant reservation for 7 PM to stay at 7 PM, regardless of politicians moving the clock forward or backward. Similarly, a dental appointment for 3 PM four months from now should stay at 3 PM even if the politicians change the offset. And politicians around the world do enjoy changing their time zone offset. This happens surprisingly often, and with less and less forewarning.
Reservations/appointments should be tracked as date and time without time zone, storing time zone separately in second column of database. These types would be TIMESTAMP WITHOUT TIME ZONE in standard SQL, and DATETIME in MySQL. And use a text type for the time zone identifier. The matching type in Java would be LocalDateTime and ZoneId. At runtime for calendaring, combine to determine a moment with a ZonedDateTime.
I and other authors have covered this many times already on Stack Overflow. So search to learn more.
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. Hibernate 5 & JPA 2.2 support java.time.
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 brought 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 (26+) bundle implementations of the java.time classes.
For earlier Android (<26), a process known as API desugaring brings a subset of the java.time functionality not originally built into Android.
If the desugaring does not offer what you need, the ThreeTenABP project adapts ThreeTen-Backport (mentioned above) to Android. See How to use ThreeTenABP….
Maybe your date format is incorrect.
reservation = System.currentTimeMillis();
UPDATE
Ok,I understand you.You should use String to receive the datetime-local value.
Because the format of datetime-local from frontend is yyyy-MM-ddTHH:mm, but the format of TimeStamp in Java(package java.sql) is yyyy-MM-ddTHH:mm:ss.
It lack the :ss, so can not receive.
Finally set timestamp after convert String to TimeStamp.
datetimeLocal = datetimeLocal.replaceAll("T", " ") + ":00";
Timestamp reservation = Timestamp.valueOf(datetimeLocal);

Converting time to UTC time goes the opposite way

I'm trying to parse an offset time using Java 8 DateTimeFormatter.
I live in EST time which is UTC-5, so when I try to convert
2019-01-22T13:09:54.620-05:00 should be --> 2019-01-22T18:09:54.620
However, with my code, it gets the current time and goes back 5 hours, resulting in 2019-01-22 08:09:54.620
Code:
import java.sql.Timestamp
import java.time._
import java.time.format.DateTimeFormatter
import scala.util.{Failure, Success, Try}
class MyTimeFormatter(parser: DateTimeFormatter) {
def parse(input: String): Try[Timestamp] = {
Try(new Timestamp(Instant.from(parser.withZone(ZoneOffset.UTC).parse(input)).toEpochMilli))
}
}
Test:
new MyTimeFormatter(DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSxxx")).parse("2019-01-22T13:09:54.620-05:00") shouldEqual Timestamp.valueOf("2019-01-22T18:09:54.620")
where parser is of type DateTimeFormatter and input string is just "2019-01-22T13:09:54.620-05:00"
I want to use this parser.parse method and not with specific temporalAccessors like OffsetDateTime.parse(input, parser) so I can handle all cases like LocalTime, LocalDateTime, ZonedDateTime, OffsetDateTime, etc..
It seems like the code just grabs the time, subtracts the offset, and brands it as UTC instead of calculating the offset with respect to UTC.
Also, is there a way to apply this UTC conversion only if the input format is of ZonedDateTime/OffsetDateTime format? If I input a LocalDateTime (which doesn't have an offset) such as 2017-01-01 12:45:00 the parser will still apply the UTC offset conversion because I told the parser to parse with zone UTC.
tl;dr
Use modern java.time classes. Convert to legacy class only if necessary to work with old code.
Specifically, parse your input string as a OffsetDateTime object, adjust to UTC by extracting an Instant, and lastly, convert to java.sql.Timestamp (only if you must).
java.sql.Timestamp ts = // Avoid using this badly-designed legacy class if at all possible.
Timestamp // You can convert back-and-forth between legacy and modern classes.
.from( // New method added to legacy class to convert from modern class.
OffsetDateTime // Represents a moment with an offset-of-UTC, a number of some hours-minutes-seconds ahead or behind UTC.
.parse( "2019-01-22T13:09:54.620-05:00" ) // Text in standard ISO 8601 format can be parsed by default, without a formatting pattern.
.toInstant() // Adjust from an offset to UTC (an offset of zero) by extracting an `Instant`.
) // Returns a `Timestamp` object. Same moment as both the `OffsetDateTime` and `Instant` objects.
;
See this code run live at IdeOne.com, resulting in:
ts.toString(): 2019-01-22 18:09:54.62
If using JDBC 4.2 or later, skip the Timestamp altogether.
myPreparedStatement.setObject( … , myOffsetDateTime ) ;
Zulu
2019-01-22T13:09:54.620-05:00 should be --> 2019-01-22T18:09:54.620
If you meant that second value to represent a moment in UTC, append the offset-from-UTC to indicate that fact. Either +00:00 or Z (pronounced “Zulu”): 2019-01-22T18:09:54.620Z.
Reporting a moment without an offset-from-UTC or time zone indicator is like reporting an amount of money without a currency indicator.
OffsetDateTime
A string with an offset-from-UTC should be parsed as a OffsetDateTime object.
Your input string happens to comply with the ISO 8601 standard formats for textual date-time values. The java.time classes use ISO 8601 formats by default when parsing/generating strings. So no need to specify a formatting pattern.
OffsetDateTime odt = OffsetDateTime.parse( "2019-01-22T13:09:54.620-05:00" ) ;
Timestamp
Apparently you want a java.sql.Timestamp object. This is one of the terrible date-time classes bundled with the earliest versions of Java. These classes are now legacy, supplanted entirely by the modern java.time classes with the adoption of JSR 310. Avoid these legacy classes whenever possible.
If you must have a Timestamp to interoperate with old code not yet updated to work with java.time, you can convert. To convert, call new methods added to the old classes.
Instant
The java.sql.Timestamp class carries a from( Instant ) method. An Instant is a moment in UTC. To adjust from the offset of our OffsetDateTime to UTC, just extract an Instant.
Instant instant = odt.toInstant() ;
java.sql.Timestamp ts = Timestamp.from( instant ) ;
We have three objects ( odt, instant, & ts ) that all represent the same moment. The first has a different wall-clock time. But all three are the same simultaneous point on the timeline.
JDBC 4.2
As of JDBC 4.2, we can directly exchange java.time objects with the database. So no need to use Timestamp.
myPreparedStatement.setObject( … , odt ) ;
…and…
OffsetDateTime odt = myResultSet.getObject( … , OffsetDateTime.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, 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.
While I cannot reproduce your issue precisely (even with changing my clock to EST), this is what I am observing:
Instant instant = Instant.from(parser.withZone(ZoneOffset.UTC).parse("2019-01-22T13:09:54.620-05:00"));
This is producing the time you would expect (2019-01-22T18:09:54.620Z).
Timestamp ts = new Timestamp(instant.toEpochMilli());
Because this is based on java.util.Date, which displays as your local time.
A better way to convert an Instant to a Timestamp is via the LocalDateTime, like so:
Timestamp ts = Timestamp.valueOf(instant.atZone(ZoneOffset.UTC).toLocalDateTime());

Postgres convert date time difference into HH:MM:SS

Ex:
startTime-EndTime
Diff is 0 years 0 months 5 days 20 hours 6 minutes 30 seconds. I want to convert this into HH:MM:SS format : 120:06:30.
tl;dr
Duration // Represent a span-of-time in terms of total number of whole seconds plus a fractional second in nanos.
.between( // Calculate elapsed time.
myResultSet.getObject( … , OffsetDateTime.class ) , // Start
myResultSet.getObject( … , OffsetDateTime.class ) , // Stop
) // Returns a `Duration` object.
.toString() // Generate text in standard ISO 8601 format of `PnYnMnDTnHnMnS`.
java.time
Doing it on the Java side is simple with a column of a data type akin to the SQL-standard TIMESTAMP WITH TIME ZONE and driver compliant with JDBC 4.2 or later (for support of the modern java.time classes).
OffsetDateTime
Retrieve your moments as OffsetDateTime objects, per JDBC 4.2 spec.
OffsetDateTime start = myResultSet.getObject( … , OffsetDateTime.class ) ;
OffsetDateTime stop = myResultSet.getObject( … , OffsetDateTime.class ) ;
Duration
Calculate elapsed time as a Duration object.
Duration d = Duration.between( start , stop ) ;
ISO 8601
Generate a standard ISO 8601 string of the format PnYnMnDTnHnMnS where the P marks the beginning (probably stands for “period” – no standardized terms in date-time handling unfortunately), and the T separates years-months-days from hours-minutes-seconds. So an hour and a half would be PT1H30M. Your example of 5 days 20hours 6minutes 30 seconds would be P5DT20H6M30S.
The java.time classes use the ISO 8601 format by default. So you generate text by simply calling toString. No need to specify a formatting pattern.
String output = d.toString() ;
P5DT20H6M30S
To parse, call parse.
Duration d = Duration.parse( "P5DT20H6M30S" ) ;
Note that Duration counts days as 24-hour chunks of time, without regard for the calendar. If you want calendar-based dates, use Period class. If you want both concepts together, use PeriodDuration class from the ThreeTen-Extra, but think twice as mixing the two concepts is usually unwise and impractical.
I strongly advise you not represent a span-of-time using the clock notation as shown in your Question. Doing so is ambiguous, error-prone with people misinterpreting the text, as I have personally seen happen in business scenarios. The standard format is much wiser.
Duration::to…Part
But if you insist on the clock-formatting, create a string by calling the to…Part methods on Duration.
String output = d.toDaysPart() + ":" + d.toHoursPart() + ":" + d.toMinutesPart() + ":" + d.toSecondsPart() + "." + d.toNanosPart() ;
toHours versus toHoursPart
If want all the days reported as hours, get total number of hours across entire span-of-time by calling toHours rather than toHoursPart. Then get the parts of minutes and seconds.
Duration d = Duration.between( start , stop ) ;
String output = d.toHours() + ":" + d.toMinutesPart() + ":" + d.toSecondsPart() ;
120:06:30
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, 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.
This can be achieved using postgresql.
To compute the difference between two timestamps as a number of seconds, use :
EXTRACT(EPOCH FROM (startTime - endTime))
Then you tun this value back to a timestamp with function TO_TIMESTAMP, and format this as a time using function TO_CHAR.
The hour part is tricky as you want to display values greater than 24 (which, as you would expect, is the maximum allowed in postgres): you need to use a little arithmetics to compute it.
SELECT CONCAT(
EXTRACT(EPOCH FROM (startTime - endTime))/60/60,
':',
TO_CHAR(TO_TIMESTAMP(
EXTRACT(EPOCH FROM (startTime - endTime))
), 'MI:SS')
)
FROM my_table

Java Spring MySQL String Timezone column between two milliseconds

I got a stored Timezone date as String on a MySQL Column with the next format:
2018-07-23T20:54:37.242Z --> start_date
What I want to do is a Between two milliseconds(or dates) like this:
SELECT * FROM activity_entity WHERE start_date BETWEEN 1532322000000 AND 1532408399000
Else, I'm using Java Spring Repository as backend where I send the parameters like this:
Date since = new Date(accessRepPOSTInDto.getSince()); //1532322000000 gives Mon Jul 23 00:00:00 CDT 2018
Date to = new Date(accessRepPOSTInDto.getTo());//1532408399000 gives Mon Jul 23 23:59:59 CDT 2018
#Query(value = "SELECT * FROM activity_entity WHERE start_date BETWEEN :since AND :too , nativeQuery = true)
ActivityEntity findBetweenDates(#Param("since") Date since, #Param("too") Date too);
Doing this returns null;
I thought MySQL can automatically format the two dates and the String column to do the Between but it looks like it doesn't.
Any help will be really grateful. Regards.
In your native query, you need to explicitly cast the value of your varchar column to the proper date/timestamp to be evaluated by the between operator. This is how your native query should look like:
SELECT * FROM activity_entity WHERE STR_TO_DATE(start_date, '%Y-%c-%eT%H:%i:%s.%fZ') BETWEEN :since AND :too
tl;dr
SQL:
SELECT * FROM tbl WHERE event >= ? AND event < ? ; -- Using Half-Open approach where beginning is *inclusive* while the ending is *exclusive*.
Java:
myPreparedStatement.setString( 1 , Instant.ofEpochMilli( 1_532_322_000_000L ).toString() ) ;
myPreparedStatement.setString( 2 , Instant.ofEpochMilli( 1_532_408_399_000L ).toString() ) ;
ISO 8601
2018-07-23T20:54:37.242Z
Text in this format is abiding by the ISO 8601 standard. That standard is the best way to represent date-time values as text. But in a database you should be using a purpose-built data type, defining a column of type akin to the SQL-standard TIMESTAMP WITH TIME ZONE. Search Stack Overflow for much more info.
The java.time classes use ISO 8601 formats by default when parsing/generating strings. So no need to specify a formatting pattern.
Instant instant = Instant.parse( "2018-07-23T20:54:37.242Z" ) ;
Count-from-epoch
You can convert your count of milliseconds since the epoch reference of first moment of 1970 in UTC using the Instant class.
Instant start = Instant.ofEpochMilli( 1_532_322_000_000L ) ;
Instant stop = Instant.ofEpochMilli( 1_532_408_399_000L ) ;
Generate strings in standard ISO 8601 format used in your database column.
String startStr = start.toString() ;
String stopStr = stop.toString() ;
Avoid legacy date-time classes
The old date-time classes that were bundled with the earliest versions of Java are bloody awful. Never use them. They have been supplanted entirely by the java.time classes.
Half-Open
What I want to do is a Between
The BETWEEN command in SQL should generally not be used with date-time values. That command is fully “closed” meaning both the beginning and the ending are inclusive.
Instead, for date-time work, it is generally best to define a span-of-time as Half-Open. In this approach the beginning is inclusive while the ending is exclusive. For example, students dismissed for lunch break from noon to 1 PM are expected back in their seats before the clock strikes 1 and the bell rings. Another example, a week starts on a Monday and runs up to, but does not include, the following Monday.
In SQL code, this means a query uses >=, AND, and <.
SELECT *
FROM tbl
WHERE event >= ?
AND event < ?
;
Since ISO 8601 format with the Z is chronological when sorted alphabetically, you can make this work with your ISO 8601 strings.
myPreparedStatement.setString( 1 , startStr ) ;
myPreparedStatement.setString( 2 , stopStr ) ;
If you had used a TIMESTAMP WITH TIME ZONE column type as discussed above, you would simply pass the Instant objects.
myPreparedStatement.setObject( 1 , start ) ;
myPreparedStatement.setObject( 2 , stop ) ;
If you really must use fully-closed approach, adjust the query operators >=, AND, and <=. Or call BETWEEN.
I am not a Spring user, cannot help you there.
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.

Comparing current time with a time of data enty in database

I have a database in which I have users with their info etc. One field is named "maeindat" and there is stored the date of the entry (creation) of that entitiy ( user )
Now I want to compare if current time is "smaller" than input date and if it is set current date into the field, but if date of entry is bigger than current date set date of entry into the field
current date < date of entry --> set current date into the field
current date > date of entry --> set date of entry in field
Bellow is the code I'm trying out...
String maeindat = rs.getString("MAEINDAT");
LocalDateTime currTime = LocalDateTime.now();
if(currTime.isBefore(maeindat)) {
currTime = maeindat;
}
else if(currTime.isAfter(maeindat)) {
maeindat = maeindat;
}
UPDATE:
String maeindat = rs.getString("MAEINDAT");
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("YYYYMMDDHH24MI");
LocalDateTime maeindatDate = LocalDateTime.parse(maeindat, formatter);
LocalDateTime currTime = LocalDateTime.now();
if(currTime.isBefore(maeindatDate)) {
currTime = maeindatDate;
}
else if (currTime.isAfter(maeindatDate)) {
maeindatDate = maeindatDate;
}
tl;dr
Comparing a LocalDateTime with current moment makes no sense logically.
myResultSet.getObject(
… ,
Instant.class // Retrieve from database column of type similar to SQL-standard `TIMESTAMP WITH TIME ZONE`.
).isBefore( Instant.now() ) // Or `isAfter` or `equals` or combine with `!` (meaning NOT before/after).
Apples & Oranges
You cannot compare strings to date-time objects. Parse your strings into date-time objects, and then you may compare.
LocalDateTime
The LocalDateTime class lacks any concept of time zone or offset-from-UTC. Use this class only if using a column in your database of a type similar to SQL-standard TIMESTAMP WITHOUT TIME ZONE.
This type is not intended to represent actual moments, specific points on the timeline. Instead this type is only a rough idea of potential moments spread over a range of about 26-27 hours.
If we say "Santa delivers the toys just after midnight on December 25th", do we mean just after midnight in Auckland, New Zealand or do we mean midnight in Kolkata India which occurs hours later? Or Paris France even more hours later? "Midnight" has no real meaning until you specify Auckland, Kolkata, or Paris.
Comparing a LocalDateTime to the current moment makes no sense! The LocalDateTime has no real meaning without the context of a time zone or offset. If you know for certain of an appropriate time zone for that value, apply a ZoneId to get a ZonedDateTime. At that point, you have an actual moment, a point on the timeline.
ZoneId z = ZoneId.of( "Asia/Kolkata" ) ;
ZonedDateTime zdt = myLocalDateTime.atZone( z ) ; // Converting vague idea about potential moments into an actual moment, a specific point on the timeline.
Instant
If you intend to represent actual moments, use SQL-standard type TIMESTAMP WITH TIME ZONE and Java type Instant (UTC) or possibly ZonedDateTime.
The Instant class represents a moment on the timeline in UTC with a resolution of nanoseconds (up to nine (9) digits of a decimal fraction).
Instant instant = myResultSet.getObject( … , Instant.class ) ;
Capture the current moment in UTC.
Instant instantNow = Instant.now() ; // Current moment in UTC.
Compare using isBefore, isAfter, equals.
boolean targetPassed = instant.isAfter( instantNow ) ;
Smart objects, not dumb strings.
With a JDBC driver complying with JDBC 4.2 and later, you may directly exchange java.time objects with your database. No need for converting to/from strings.
LocalDateTime ldt = myResultSet.getObject( … , LocalDateTime.class ) ; // For database column of type like `TIMESTAMP WITHOUT TIME ZONE`.
Or…
Instant instant = myResultSet.getObject( … , Instant.class ) ; // For database column of type like `TIMESTAMP WITH TIME ZONE`.
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, 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.

Categories