0

In my Java Spring MVC Web Application, I am trying to write a program to save some data with a time stamp along with it. But I have a specific time period which I have to exclude.

For example, I have the following timestamp: Sat Jul 28 17:03:00 IST 2018 which is a Java Date object. Before saving to the database I have to check if this time comes inside a specified range if then I have to get the next minute after the end of the time range.

But the time range is a string of the following format:

String startTime =  "5:03 PM";
String endTime = "5:10 PM";

So my if my timeStamp falls in between this time, my timestamp should be updated as Sat Jul 28 17:11:00 IST 2018.

I am finding now way to compare the two-time values since one is a string and the other is a time stamp.

Is there any way to convert String endTime = "5:10 PM"; to Sat Jul 28 17:11:00 IST 2018 or just compare the time part, calculate the difference in minutes and add that to the timestamp.

Geo Thomas
  • 1,139
  • 3
  • 26
  • 59
  • From where do you have the values `startTime` and `endTime`? Is it a user input? – Lino Jul 27 '18 at 11:02
  • 1
    Do you already know the "new" (as of java 8) time API? See e.g. [ZonedDateTime](https://docs.oracle.com/javase/10/docs/api/java/time/ZonedDateTime.html) and [Period](https://docs.oracle.com/javase/10/docs/api/java/time/Period.html) – Hulk Jul 27 '18 at 11:03
  • @Lino , those are user inputs, i can only collect them as string – Geo Thomas Jul 27 '18 at 11:10
  • @Hulk, i use java 7. I usualy use joda for datetime related operations – Geo Thomas Jul 27 '18 at 11:11
  • For calculating a `Duration` between `DateTimes`: [Related question](https://stackoverflow.com/questions/12851934/how-to-find-difference-between-two-joda-time-datetimes-in-minutes/12852021) – Hulk Jul 27 '18 at 12:39
  • Assuming your `Strings` contain local times, [this related question](https://stackoverflow.com/questions/33106665/parsing-hhmm-with-two-digits-minute-to-localtime-with-jodatime) about parsing `LocalTime` might help. – Hulk Jul 27 '18 at 12:52
  • @Hulk I do not see how `Duration` applies here. That class represents a span-of-time not attached to the timeline. – Basil Bourque Jul 27 '18 at 20:08

2 Answers2

5

Avoid legacy date-time classes

Avoid the troublesome old legacy date-time classes such as java.util.Date. Use only java.time classes. Likewise, the Joda-Time project too is now supplanted by the java.time classes, both having been created by the same man, Stephen Colebourne.

Instant

Convert your Date to Instant. Both classes represent a moment in UTC, always in UTC, despite the Date::toString method lying to you.

Convert using new methods added to the old classes.

Instant instant = myJavaUtilDate.toInstant() ;

ZonedDateTime

Apply a time zone or offset-from-UTC for the wall-clock time intended by you pair of time-of-day strings. Did you mean 5 PM in New York, or 5 PM in Tunisia, or 5 PM in India?

Specify a proper time zone name in the format of continent/region, such as America/Montreal, Africa/Casablanca, or Pacific/Auckland. Never use the 3-4 letter abbreviation such as EST or IST as they are not true time zones, not standardized, and not even unique(!).

ZoneId z = ZoneId.of( "Asia/Kolkata" ) ;  // Or "Pacific/Auckland" etc. 
ZonedDateTime zdt = instant.atZone( z ) ;

Extract the time-of-day without date and without zone.

LocalTime lt = zdt.toLocalTime() ;

LocalTime

Parse your limits as LocalTime objects.

DateTimeFormatter f = DateTimeFormatter.ofPattern( "h:mm a" , Locale.US ) ;

LocalTime start = LocalTime.parse( "5:03 PM" , f ) ;
LocalTime stop = LocalTime.parse( "5:11 PM" , f ) ;

Half-Open

Generally best to use Half-Open approach to defining a span of time. This means the beginning is inclusive while the ending is exclusive. So test for “less than eleven past five” if you want to exclude all of the tenth minute.

Tip: A shorter way of saying “Is equal to or is after” is “Is not before”.

if ( ( ! lt.isBefore( start ) ) && lt.isBefore( stop ) ) {
    zdt = zdt.with( stop ) ;  // Change to a different time-of-day. 
}

If that time-of-day on that date in that zone is invalid, the ZonedDateTime class makes an adjustment as needed.

Database

For saving to a database in a column of type TIMESTAMP WITH TIME ZONE, let's adjust our moment into UTC by extracting an Instant.

Instant instantForDatabase = zdt.toInstant() ;
…
myPreparedStatement.setObject( … , instantForDatabase ) ;

Retrieval from database.

Instant instantFromDatabase = myResultSet.getObject( … , Instant.class ) ;
ZoneId zMontreal = ZoneId.of( "America/Montreal" ) ;  // Or "Asia/Kolkata" etc.
ZondDateTime zdtMontreal = instantFromDatabase.atZone( zMontreal ) ;  

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?

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.

Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
0

You have lots of options, one of the simpler is:

1)- You could convert the TimeStamp to a LocalDateTime/Calendar object and then get the hour and minute.

LocalDateTime localdt = sqlTimestamp.toLocalDateTime();
int hour = localdt.getHour();
int minute = localdt.getMinute();

2)-Then you can parse the string and compare the results.

- You could also convert the strings to timestamp, for that you would need the start and end of day and to parse the strings.

- Nonetheless, it sounds like the data types you selected will bring trouble later.