-3

i wanted to take an input of date and time in the below format and need to calculate the time difference between two, can anyone suggest how to take below string as input and calculate the time difference.

user defined datetime input in java

String startTime= "11/27/2018+09:00:00";
String endTime= "11/28/2018+13:00:00";

The + is a separator (not a sign as in plus or minus).

Ole V.V.
  • 81,772
  • 15
  • 137
  • 161
Roopesh
  • 1
  • 3
  • 1
    `DateTimeFormatter` and `Duration` from the `java.time` API – MadProgrammer Nov 27 '18 at 03:23
  • 1
    search for 1) java input string from console 2) java parse string to date 3) java difference between LocalDate(s) – Kartik Nov 27 '18 at 03:24
  • @Roopesh Have you tried anything from yourself? – Abhinav Nov 27 '18 at 04:45
  • What is the expected result in this case? Sorry, it’s not immediately clear since I don’t see any time of day in your input. 20 hours? 24 hours? 1 day? Welcome to Stack Overflow. – Ole V.V. Nov 27 '18 at 05:15
  • @Ole it’s in 24hours format. – Roopesh Nov 27 '18 at 05:34
  • I didn’t get that. Sorry, but are you sure you did? Asking because I think that `+09:00` looks like a UTC offset, not a time of day. Your format seems to resemble [`DateTimeFormatter.ISO_OFFSET_DATE`](https://docs.oracle.com/javase/10/docs/api/java/time/format/DateTimeFormatter.html#ISO_OFFSET_DATE), only with `11/27/2018` instead of `2018-11-27`. – Ole V.V. Nov 27 '18 at 05:45
  • 1
    @Ole thanks for correcting me actually the format is “MM/DD/YYYY+09:00:00” + is string separater. – Roopesh Nov 27 '18 at 06:23
  • Please fix the broken Shift key on your keyboard. This site is meant to be more like Wikipedia, a resource for posterity, not a casual chat room. – Basil Bourque Nov 27 '18 at 06:30

2 Answers2

1

Senseless input

String startTime= "11/27/2018+09:00";
String endTime= "11/28/2018+13:00";

These inputs do not make sense. Applying an offset-from-UTC such as +09:00 to a date such as 11/27/2018 has no meaning.

For an offset to have meaning, you need a date and a time-of-day.

We can make a guess and assume the people sending the data meant the first moment of the day. If so, they should have said so by including that in the data.

The trick here is that some dates in some time zones do not always start at 00:00:00 time-of-day. Anomalies such as Daylight Saving Time (DST) mean the day may start at a time such as 01:00:00. Unfortunately, your input has only an offset (a number of hours-minutes-seconds) rather than a time zone (Continent/Region name). A time zone is a history of the past, present, and future changes to the offset used by the people of a particular region. Without a time zone, we cannot look up the rules to know the anomalies.

The best you could do is assume the day starts at 00:00:00 and ignore the reality of any anomalies. But this is guesswork and inadvisable. The real solution is to educate the publisher of your data about two things when exchanging date-time values: (a) Use UTC rather than an offset or zone, and (b) write strings in standard ISO 8601 format.

Guesswork

If correcting the source of this data is not feasible, then we can plod on with guesswork.

Extract the date, separate from offset.

String input = "11/27/2018+09:00";
DateTimeFormatter f = DateTimeFormatter.ofPattern( "MM/dd/uuuu" );
LocalDate localDate = LocalDate.parse( input.substring( 0 , 10 ) , f );
ZoneOffset zoneOffset = ZoneOffset.of( input.substring( 11 ) );

localDate.toString(): 2018-11-27

zoneOffset.toString(): +09:00

OffsetDateTime odt = OffsetDateTime.of( localDate , LocalTime.MIN , zoneOffset );

2018-11-27T00:00+09:00

We can calculate elapsed time as a Duration. But beware, without the context of time zones, we cannot account for any anomalies that may be occurring in this time period, as discussed above. With only offsets rather than zones, calculations are made using generic 24-hour days. So, again, this is just sloppy guesswork, not a reliable solution.

Duration d = Duration.between( odt , odtLater ) ; 

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

In java 8 there is:
LocalDateTime: use this if you need to deal with date and time.
LocalDate: use this if you need to deal with date only.
ZonedDateTime: use this if you need to deal with date time with time zone.
OffsetDateTime: use this if you need to deal with date time with offset. (the most suitable for your case)

Your case is only use Date and Offset, it's a bit tricky since time zone and offset can only be applied to LocalDateTime (not only date).

However, I think you can solved it like this:

Create a method that convert your date string into OffsetDateTime like this:

private static OffsetDateTime createZonedDateTime (String dateWithTimeOffset)
{
    //TODO: assert that dateWithTimeOffset is valid
    String date = dateWithTimeOffset.substring (0, 10);
    String timeOffset = dateWithTimeOffset.substring (10, 13);

    //define your date pattern
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern ("MM/dd/yyyy");

    return LocalDate.parse (date, formatter) // create LocalDate
                .atStartOfDay () // convert it to LocalDateTime with time 00:00:00
                .atOffset (ZoneOffset.of(timeOffset)); // apply the offset
}

Then you can simple create your OffsetDateTime like this:

OffsetDateTime startTime = stringToZonedDateTime ("11/27/2018+09:00");  
OffsetDateTime endTime = stringToZonedDateTime ("11/28/2018+13:00");

You can create duration using OffsetDateTime like this:

Duration duration = Duration.between (startTime, endTime);

Duration have everything you need related with time duration, for example:

duration.toHours () // will give you the hour duration
efmalik
  • 110
  • 1
  • 10
  • @karthik I tried the other way by taking the System time and calculating the difference, and am not expecting the program to be done by other, I just want to know the methods how to implement. – Roopesh Nov 27 '18 at 05:50
  • @BasilBourque, Thanks for your input. I have updated my answer. And thanks for point out `OffsetDateTime` I am not aware of this before. – efmalik Nov 27 '18 at 08:18