LocalTime() difference between two times










2














I have a flight itinerary program where I need to get difference between departure and arrival time. I get these specified times as String from the data. Here is my problem:



import static java.time.temporal.ChronoUnit.MINUTES;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;

public class test2
public static void main(String args)

DateTimeFormatter dateFormat = DateTimeFormatter.ofPattern("HHmm");
LocalTime departure = LocalTime.parse("1139", dateFormat);
LocalTime arrival = LocalTime.parse("1435", dateFormat);
LocalTime a = LocalTime.parse("0906", dateFormat);
System.out.println(MINUTES.between(departure, arrival));
System.out.println(MINUTES.between(arrival, a));




Output:



176
-329


The first time returns the difference between 11:39 and 14:35 just fine. But the second difference is only 5 hours while it should be 19 hours. How can I fix this, what am I doing wrong here?



Any help would be greatly appreciated.



EDIT: I am using graphs to store my data in. An example of a shortest route between two airports is like this:



Route for Edinburgh to Sydney
1 Edinburgh, 1139, TK3245, Istanbul, 1435
2 Istanbul, 0906, TK4557, Singapore, 1937
3 Singapore, 0804, QF1721, Sydney, 1521


These are the 3 flights that takes us from EDI to SYD. The format of the output above is (City, Departure Time, Flight No., Destination, Arrival Time).










share|improve this question



















  • 2




    You know, the problem with time is just the period from midnight AM to midnight PM, it has no concept of what exists beyond those boundaries. Instead, you should be using a LocalDateTime which allows for the transition from one day to another
    – MadProgrammer
    Nov 12 '18 at 0:05







  • 1




    While your example is probably pretty simple, I would recommend having a look at ZonedDateTime, as you might be passing between different time zones, making the calculations rather ... weird :P (not unheard of arriving before you left 🤪)
    – MadProgrammer
    Nov 12 '18 at 0:06







  • 1




    I don't see the issue. The results you get are correct. Why the difference between 09:05 to 14:35 should be 19 hours?
    – dorony
    Nov 12 '18 at 0:11











  • @dorony Sorry I made a mistake and forgot to change my code before posting. The difference should be from 14:35 to 09:05. In this case, as MadProgrammer has mentioned, the date is changing so the values are getting lost or something. I tried the suggestion MadProgrammer suggested, but LocalDateTime only works if I provide the date with it (at least it does as far as I have tested it right now). The data I am getting does not provide me with date, it's simply two times. The dates do not matter.
    – Naeem Khan
    Nov 12 '18 at 0:25






  • 2




    If the result you get is below zero then sum it with 24*60 and you will get the correct result.
    – dorony
    Nov 12 '18 at 0:32















2














I have a flight itinerary program where I need to get difference between departure and arrival time. I get these specified times as String from the data. Here is my problem:



import static java.time.temporal.ChronoUnit.MINUTES;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;

public class test2
public static void main(String args)

DateTimeFormatter dateFormat = DateTimeFormatter.ofPattern("HHmm");
LocalTime departure = LocalTime.parse("1139", dateFormat);
LocalTime arrival = LocalTime.parse("1435", dateFormat);
LocalTime a = LocalTime.parse("0906", dateFormat);
System.out.println(MINUTES.between(departure, arrival));
System.out.println(MINUTES.between(arrival, a));




Output:



176
-329


The first time returns the difference between 11:39 and 14:35 just fine. But the second difference is only 5 hours while it should be 19 hours. How can I fix this, what am I doing wrong here?



Any help would be greatly appreciated.



EDIT: I am using graphs to store my data in. An example of a shortest route between two airports is like this:



Route for Edinburgh to Sydney
1 Edinburgh, 1139, TK3245, Istanbul, 1435
2 Istanbul, 0906, TK4557, Singapore, 1937
3 Singapore, 0804, QF1721, Sydney, 1521


These are the 3 flights that takes us from EDI to SYD. The format of the output above is (City, Departure Time, Flight No., Destination, Arrival Time).










share|improve this question



















  • 2




    You know, the problem with time is just the period from midnight AM to midnight PM, it has no concept of what exists beyond those boundaries. Instead, you should be using a LocalDateTime which allows for the transition from one day to another
    – MadProgrammer
    Nov 12 '18 at 0:05







  • 1




    While your example is probably pretty simple, I would recommend having a look at ZonedDateTime, as you might be passing between different time zones, making the calculations rather ... weird :P (not unheard of arriving before you left 🤪)
    – MadProgrammer
    Nov 12 '18 at 0:06







  • 1




    I don't see the issue. The results you get are correct. Why the difference between 09:05 to 14:35 should be 19 hours?
    – dorony
    Nov 12 '18 at 0:11











  • @dorony Sorry I made a mistake and forgot to change my code before posting. The difference should be from 14:35 to 09:05. In this case, as MadProgrammer has mentioned, the date is changing so the values are getting lost or something. I tried the suggestion MadProgrammer suggested, but LocalDateTime only works if I provide the date with it (at least it does as far as I have tested it right now). The data I am getting does not provide me with date, it's simply two times. The dates do not matter.
    – Naeem Khan
    Nov 12 '18 at 0:25






  • 2




    If the result you get is below zero then sum it with 24*60 and you will get the correct result.
    – dorony
    Nov 12 '18 at 0:32













2












2








2







I have a flight itinerary program where I need to get difference between departure and arrival time. I get these specified times as String from the data. Here is my problem:



import static java.time.temporal.ChronoUnit.MINUTES;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;

public class test2
public static void main(String args)

DateTimeFormatter dateFormat = DateTimeFormatter.ofPattern("HHmm");
LocalTime departure = LocalTime.parse("1139", dateFormat);
LocalTime arrival = LocalTime.parse("1435", dateFormat);
LocalTime a = LocalTime.parse("0906", dateFormat);
System.out.println(MINUTES.between(departure, arrival));
System.out.println(MINUTES.between(arrival, a));




Output:



176
-329


The first time returns the difference between 11:39 and 14:35 just fine. But the second difference is only 5 hours while it should be 19 hours. How can I fix this, what am I doing wrong here?



Any help would be greatly appreciated.



EDIT: I am using graphs to store my data in. An example of a shortest route between two airports is like this:



Route for Edinburgh to Sydney
1 Edinburgh, 1139, TK3245, Istanbul, 1435
2 Istanbul, 0906, TK4557, Singapore, 1937
3 Singapore, 0804, QF1721, Sydney, 1521


These are the 3 flights that takes us from EDI to SYD. The format of the output above is (City, Departure Time, Flight No., Destination, Arrival Time).










share|improve this question















I have a flight itinerary program where I need to get difference between departure and arrival time. I get these specified times as String from the data. Here is my problem:



import static java.time.temporal.ChronoUnit.MINUTES;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;

public class test2
public static void main(String args)

DateTimeFormatter dateFormat = DateTimeFormatter.ofPattern("HHmm");
LocalTime departure = LocalTime.parse("1139", dateFormat);
LocalTime arrival = LocalTime.parse("1435", dateFormat);
LocalTime a = LocalTime.parse("0906", dateFormat);
System.out.println(MINUTES.between(departure, arrival));
System.out.println(MINUTES.between(arrival, a));




Output:



176
-329


The first time returns the difference between 11:39 and 14:35 just fine. But the second difference is only 5 hours while it should be 19 hours. How can I fix this, what am I doing wrong here?



Any help would be greatly appreciated.



EDIT: I am using graphs to store my data in. An example of a shortest route between two airports is like this:



Route for Edinburgh to Sydney
1 Edinburgh, 1139, TK3245, Istanbul, 1435
2 Istanbul, 0906, TK4557, Singapore, 1937
3 Singapore, 0804, QF1721, Sydney, 1521


These are the 3 flights that takes us from EDI to SYD. The format of the output above is (City, Departure Time, Flight No., Destination, Arrival Time).







java localtime time-format






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 12 '18 at 0:30

























asked Nov 12 '18 at 0:02









Naeem Khan

649




649







  • 2




    You know, the problem with time is just the period from midnight AM to midnight PM, it has no concept of what exists beyond those boundaries. Instead, you should be using a LocalDateTime which allows for the transition from one day to another
    – MadProgrammer
    Nov 12 '18 at 0:05







  • 1




    While your example is probably pretty simple, I would recommend having a look at ZonedDateTime, as you might be passing between different time zones, making the calculations rather ... weird :P (not unheard of arriving before you left 🤪)
    – MadProgrammer
    Nov 12 '18 at 0:06







  • 1




    I don't see the issue. The results you get are correct. Why the difference between 09:05 to 14:35 should be 19 hours?
    – dorony
    Nov 12 '18 at 0:11











  • @dorony Sorry I made a mistake and forgot to change my code before posting. The difference should be from 14:35 to 09:05. In this case, as MadProgrammer has mentioned, the date is changing so the values are getting lost or something. I tried the suggestion MadProgrammer suggested, but LocalDateTime only works if I provide the date with it (at least it does as far as I have tested it right now). The data I am getting does not provide me with date, it's simply two times. The dates do not matter.
    – Naeem Khan
    Nov 12 '18 at 0:25






  • 2




    If the result you get is below zero then sum it with 24*60 and you will get the correct result.
    – dorony
    Nov 12 '18 at 0:32












  • 2




    You know, the problem with time is just the period from midnight AM to midnight PM, it has no concept of what exists beyond those boundaries. Instead, you should be using a LocalDateTime which allows for the transition from one day to another
    – MadProgrammer
    Nov 12 '18 at 0:05







  • 1




    While your example is probably pretty simple, I would recommend having a look at ZonedDateTime, as you might be passing between different time zones, making the calculations rather ... weird :P (not unheard of arriving before you left 🤪)
    – MadProgrammer
    Nov 12 '18 at 0:06







  • 1




    I don't see the issue. The results you get are correct. Why the difference between 09:05 to 14:35 should be 19 hours?
    – dorony
    Nov 12 '18 at 0:11











  • @dorony Sorry I made a mistake and forgot to change my code before posting. The difference should be from 14:35 to 09:05. In this case, as MadProgrammer has mentioned, the date is changing so the values are getting lost or something. I tried the suggestion MadProgrammer suggested, but LocalDateTime only works if I provide the date with it (at least it does as far as I have tested it right now). The data I am getting does not provide me with date, it's simply two times. The dates do not matter.
    – Naeem Khan
    Nov 12 '18 at 0:25






  • 2




    If the result you get is below zero then sum it with 24*60 and you will get the correct result.
    – dorony
    Nov 12 '18 at 0:32







2




2




You know, the problem with time is just the period from midnight AM to midnight PM, it has no concept of what exists beyond those boundaries. Instead, you should be using a LocalDateTime which allows for the transition from one day to another
– MadProgrammer
Nov 12 '18 at 0:05





You know, the problem with time is just the period from midnight AM to midnight PM, it has no concept of what exists beyond those boundaries. Instead, you should be using a LocalDateTime which allows for the transition from one day to another
– MadProgrammer
Nov 12 '18 at 0:05





1




1




While your example is probably pretty simple, I would recommend having a look at ZonedDateTime, as you might be passing between different time zones, making the calculations rather ... weird :P (not unheard of arriving before you left 🤪)
– MadProgrammer
Nov 12 '18 at 0:06





While your example is probably pretty simple, I would recommend having a look at ZonedDateTime, as you might be passing between different time zones, making the calculations rather ... weird :P (not unheard of arriving before you left 🤪)
– MadProgrammer
Nov 12 '18 at 0:06





1




1




I don't see the issue. The results you get are correct. Why the difference between 09:05 to 14:35 should be 19 hours?
– dorony
Nov 12 '18 at 0:11





I don't see the issue. The results you get are correct. Why the difference between 09:05 to 14:35 should be 19 hours?
– dorony
Nov 12 '18 at 0:11













@dorony Sorry I made a mistake and forgot to change my code before posting. The difference should be from 14:35 to 09:05. In this case, as MadProgrammer has mentioned, the date is changing so the values are getting lost or something. I tried the suggestion MadProgrammer suggested, but LocalDateTime only works if I provide the date with it (at least it does as far as I have tested it right now). The data I am getting does not provide me with date, it's simply two times. The dates do not matter.
– Naeem Khan
Nov 12 '18 at 0:25




@dorony Sorry I made a mistake and forgot to change my code before posting. The difference should be from 14:35 to 09:05. In this case, as MadProgrammer has mentioned, the date is changing so the values are getting lost or something. I tried the suggestion MadProgrammer suggested, but LocalDateTime only works if I provide the date with it (at least it does as far as I have tested it right now). The data I am getting does not provide me with date, it's simply two times. The dates do not matter.
– Naeem Khan
Nov 12 '18 at 0:25




2




2




If the result you get is below zero then sum it with 24*60 and you will get the correct result.
– dorony
Nov 12 '18 at 0:32




If the result you get is below zero then sum it with 24*60 and you will get the correct result.
– dorony
Nov 12 '18 at 0:32












2 Answers
2






active

oldest

votes


















3














The total number of minutes in 24 hours is 1440. So when the difference is below zero (but you need a positive one) then you should add a whole day to your result:



int diff = MINUTES.between(arrival, a);
if (diff < 0)
diff += 1440;



You can achieve the same thing using this:



int diff = (MINUTES.between(arrival, a) + 1440) % 1440;





share|improve this answer






















  • Thank you so much! This fixed it. Can you please explain how that works though?
    – Naeem Khan
    Nov 12 '18 at 0:36










  • @NaeemKhan Glad it helped. Check the updates. If you want a more detailed explanation then read about modular addition/substraction.
    – ETO
    Nov 12 '18 at 1:00










  • I understand that part. I was 5 AM that night so my brain wasnt functioning properly. I didn't realize that 1440 was the number of minutes in the day. Thank you for the explanation.
    – Naeem Khan
    Nov 13 '18 at 3:09


















2














The primary issue at hand is LocalTime is only a representation of time between midnight AM to midnight PM, it has no concept of any range beyond those bounds.



What you really need is a date value, associated with the time value, this would then allow you to calculate durations beyond a 24 hour period.



Failing that, you will need to "fudge" the values yourself. This means, that when the next time is less than previous time, you will need to manually add an additional period, maybe a day.



There are probably a few ways to do this, this is just one.



It takes a ZonedDateTime (set to the current date) and uses it as a "anchor" date. Each Time of the schedule is then applied to this. When it detects that last arrival time is before the next departure time, it adds a day to the values.



import java.time.Duration;
import java.time.LocalTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

public class Test

public static void main(String args)
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("HHmm");

List<Schedule> route = new ArrayList<>(4);
route.add(new Schedule(LocalTime.parse("1139", formatter), LocalTime.parse("1435", formatter)));
route.add(new Schedule(LocalTime.parse("0906", formatter), LocalTime.parse("1937", formatter)));
route.add(new Schedule(LocalTime.parse("0804", formatter), LocalTime.parse("1521", formatter)));

// Anchor time...
ZonedDateTime zdt = ZonedDateTime.now(ZoneId.of("UTC"));
ZonedDateTime lastArrival = null;
Duration totalDuration = Duration.ZERO;
for (Schedule schedule : route)
ZonedDateTime depart = zdt.with(schedule.getDepart());
ZonedDateTime arrive = zdt.with(schedule.getArrive());

if (lastArrival != null)
if (lastArrival.isAfter(depart))
// Most likely, we've shifted to a new day...
// Updat the anchor and target values
zdt = zdt.plusDays(1);
depart = depart.plusDays(1);
arrive = arrive.plusDays(1);

Duration duration = Duration.between(lastArrival, depart);
totalDuration = totalDuration.plus(duration);
System.out.println("...Wait for " + duration.toHoursPart() + "h " + duration.toMinutesPart() + "m");


Duration duration = Duration.between(depart, arrive);
System.out.println(duration.toHoursPart() + "h " + duration.toMinutesPart() + "m");
totalDuration = totalDuration.plus(duration);

lastArrival = arrive;

System.out.println("Total duration of " + totalDuration.toHoursPart() + "d " + totalDuration.toHoursPart() + "h " + totalDuration.toMinutesPart() + "m");



public static class Schedule

private LocalTime depart;
private LocalTime arrive;

public Schedule(LocalTime depart, LocalTime arrive)
this.depart = depart;
this.arrive = arrive;


public LocalTime getDepart()
return depart;


public LocalTime getArrive()
return arrive;






Which will output...



2h 56m
...Wait for 18h 31m
10h 31m
...Wait for 12h 27m
7h 17m
Total duration of 3d 3h 42m


But why do this? Because date/time manipulation is a complete mess, with leap seconds, years and other stupid rules which are meant to stop it from all falling apart into chaos (this is why there are no flights at 12:00 :/) ... and don't get me started on daylight savings...



The Java date/time API takes care of all of this for us.



I've chosen to maintain the date/time information in a single unit of work, ie UTC, which allows all the values to have some kind of useful meaning. You could easily use a different anchor time as well as convert to a different time zone for use in presentation - so you could display the times in local time at the destination, but the calculations would continue to be done against a single point of truth.






share|improve this answer






















  • to be picky, the primary issue is, IMHO, that we have no date information in the input data - logically, assuming normal flights, if the arrival time is before the departure one, we can assume it must be one day later... but if it is a ship travel, it could be a couple of days later...(most flight plans I know of have something like a +1 to indicate it is the next day)
    – Carlos Heuberger
    Nov 12 '18 at 8:15










  • @CarlosHeuberger My "preferred" solution would have the values with both date and times in a single timezone, so you don't end up with to much weirdness, but, it could still be physically possible to arrive before you left even in that scenario. What I'm "trying" to do is get people to "stop" performing mathematic manipulation of date/time values, as that's even worse (IMO)
    – MadProgrammer
    Nov 12 '18 at 8:33










  • I will look into implementing this with my program when it is finished, for now I need to focus on finishing it. Thank you so much for this!
    – Naeem Khan
    Nov 14 '18 at 10:26










Your Answer






StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");

StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);

else
createEditor();

);

function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);



);













draft saved

draft discarded


















StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53254475%2flocaltime-difference-between-two-times%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown

























2 Answers
2






active

oldest

votes








2 Answers
2






active

oldest

votes









active

oldest

votes






active

oldest

votes









3














The total number of minutes in 24 hours is 1440. So when the difference is below zero (but you need a positive one) then you should add a whole day to your result:



int diff = MINUTES.between(arrival, a);
if (diff < 0)
diff += 1440;



You can achieve the same thing using this:



int diff = (MINUTES.between(arrival, a) + 1440) % 1440;





share|improve this answer






















  • Thank you so much! This fixed it. Can you please explain how that works though?
    – Naeem Khan
    Nov 12 '18 at 0:36










  • @NaeemKhan Glad it helped. Check the updates. If you want a more detailed explanation then read about modular addition/substraction.
    – ETO
    Nov 12 '18 at 1:00










  • I understand that part. I was 5 AM that night so my brain wasnt functioning properly. I didn't realize that 1440 was the number of minutes in the day. Thank you for the explanation.
    – Naeem Khan
    Nov 13 '18 at 3:09















3














The total number of minutes in 24 hours is 1440. So when the difference is below zero (but you need a positive one) then you should add a whole day to your result:



int diff = MINUTES.between(arrival, a);
if (diff < 0)
diff += 1440;



You can achieve the same thing using this:



int diff = (MINUTES.between(arrival, a) + 1440) % 1440;





share|improve this answer






















  • Thank you so much! This fixed it. Can you please explain how that works though?
    – Naeem Khan
    Nov 12 '18 at 0:36










  • @NaeemKhan Glad it helped. Check the updates. If you want a more detailed explanation then read about modular addition/substraction.
    – ETO
    Nov 12 '18 at 1:00










  • I understand that part. I was 5 AM that night so my brain wasnt functioning properly. I didn't realize that 1440 was the number of minutes in the day. Thank you for the explanation.
    – Naeem Khan
    Nov 13 '18 at 3:09













3












3








3






The total number of minutes in 24 hours is 1440. So when the difference is below zero (but you need a positive one) then you should add a whole day to your result:



int diff = MINUTES.between(arrival, a);
if (diff < 0)
diff += 1440;



You can achieve the same thing using this:



int diff = (MINUTES.between(arrival, a) + 1440) % 1440;





share|improve this answer














The total number of minutes in 24 hours is 1440. So when the difference is below zero (but you need a positive one) then you should add a whole day to your result:



int diff = MINUTES.between(arrival, a);
if (diff < 0)
diff += 1440;



You can achieve the same thing using this:



int diff = (MINUTES.between(arrival, a) + 1440) % 1440;






share|improve this answer














share|improve this answer



share|improve this answer








edited Nov 12 '18 at 0:46

























answered Nov 12 '18 at 0:33









ETO

1,722421




1,722421











  • Thank you so much! This fixed it. Can you please explain how that works though?
    – Naeem Khan
    Nov 12 '18 at 0:36










  • @NaeemKhan Glad it helped. Check the updates. If you want a more detailed explanation then read about modular addition/substraction.
    – ETO
    Nov 12 '18 at 1:00










  • I understand that part. I was 5 AM that night so my brain wasnt functioning properly. I didn't realize that 1440 was the number of minutes in the day. Thank you for the explanation.
    – Naeem Khan
    Nov 13 '18 at 3:09
















  • Thank you so much! This fixed it. Can you please explain how that works though?
    – Naeem Khan
    Nov 12 '18 at 0:36










  • @NaeemKhan Glad it helped. Check the updates. If you want a more detailed explanation then read about modular addition/substraction.
    – ETO
    Nov 12 '18 at 1:00










  • I understand that part. I was 5 AM that night so my brain wasnt functioning properly. I didn't realize that 1440 was the number of minutes in the day. Thank you for the explanation.
    – Naeem Khan
    Nov 13 '18 at 3:09















Thank you so much! This fixed it. Can you please explain how that works though?
– Naeem Khan
Nov 12 '18 at 0:36




Thank you so much! This fixed it. Can you please explain how that works though?
– Naeem Khan
Nov 12 '18 at 0:36












@NaeemKhan Glad it helped. Check the updates. If you want a more detailed explanation then read about modular addition/substraction.
– ETO
Nov 12 '18 at 1:00




@NaeemKhan Glad it helped. Check the updates. If you want a more detailed explanation then read about modular addition/substraction.
– ETO
Nov 12 '18 at 1:00












I understand that part. I was 5 AM that night so my brain wasnt functioning properly. I didn't realize that 1440 was the number of minutes in the day. Thank you for the explanation.
– Naeem Khan
Nov 13 '18 at 3:09




I understand that part. I was 5 AM that night so my brain wasnt functioning properly. I didn't realize that 1440 was the number of minutes in the day. Thank you for the explanation.
– Naeem Khan
Nov 13 '18 at 3:09













2














The primary issue at hand is LocalTime is only a representation of time between midnight AM to midnight PM, it has no concept of any range beyond those bounds.



What you really need is a date value, associated with the time value, this would then allow you to calculate durations beyond a 24 hour period.



Failing that, you will need to "fudge" the values yourself. This means, that when the next time is less than previous time, you will need to manually add an additional period, maybe a day.



There are probably a few ways to do this, this is just one.



It takes a ZonedDateTime (set to the current date) and uses it as a "anchor" date. Each Time of the schedule is then applied to this. When it detects that last arrival time is before the next departure time, it adds a day to the values.



import java.time.Duration;
import java.time.LocalTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

public class Test

public static void main(String args)
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("HHmm");

List<Schedule> route = new ArrayList<>(4);
route.add(new Schedule(LocalTime.parse("1139", formatter), LocalTime.parse("1435", formatter)));
route.add(new Schedule(LocalTime.parse("0906", formatter), LocalTime.parse("1937", formatter)));
route.add(new Schedule(LocalTime.parse("0804", formatter), LocalTime.parse("1521", formatter)));

// Anchor time...
ZonedDateTime zdt = ZonedDateTime.now(ZoneId.of("UTC"));
ZonedDateTime lastArrival = null;
Duration totalDuration = Duration.ZERO;
for (Schedule schedule : route)
ZonedDateTime depart = zdt.with(schedule.getDepart());
ZonedDateTime arrive = zdt.with(schedule.getArrive());

if (lastArrival != null)
if (lastArrival.isAfter(depart))
// Most likely, we've shifted to a new day...
// Updat the anchor and target values
zdt = zdt.plusDays(1);
depart = depart.plusDays(1);
arrive = arrive.plusDays(1);

Duration duration = Duration.between(lastArrival, depart);
totalDuration = totalDuration.plus(duration);
System.out.println("...Wait for " + duration.toHoursPart() + "h " + duration.toMinutesPart() + "m");


Duration duration = Duration.between(depart, arrive);
System.out.println(duration.toHoursPart() + "h " + duration.toMinutesPart() + "m");
totalDuration = totalDuration.plus(duration);

lastArrival = arrive;

System.out.println("Total duration of " + totalDuration.toHoursPart() + "d " + totalDuration.toHoursPart() + "h " + totalDuration.toMinutesPart() + "m");



public static class Schedule

private LocalTime depart;
private LocalTime arrive;

public Schedule(LocalTime depart, LocalTime arrive)
this.depart = depart;
this.arrive = arrive;


public LocalTime getDepart()
return depart;


public LocalTime getArrive()
return arrive;






Which will output...



2h 56m
...Wait for 18h 31m
10h 31m
...Wait for 12h 27m
7h 17m
Total duration of 3d 3h 42m


But why do this? Because date/time manipulation is a complete mess, with leap seconds, years and other stupid rules which are meant to stop it from all falling apart into chaos (this is why there are no flights at 12:00 :/) ... and don't get me started on daylight savings...



The Java date/time API takes care of all of this for us.



I've chosen to maintain the date/time information in a single unit of work, ie UTC, which allows all the values to have some kind of useful meaning. You could easily use a different anchor time as well as convert to a different time zone for use in presentation - so you could display the times in local time at the destination, but the calculations would continue to be done against a single point of truth.






share|improve this answer






















  • to be picky, the primary issue is, IMHO, that we have no date information in the input data - logically, assuming normal flights, if the arrival time is before the departure one, we can assume it must be one day later... but if it is a ship travel, it could be a couple of days later...(most flight plans I know of have something like a +1 to indicate it is the next day)
    – Carlos Heuberger
    Nov 12 '18 at 8:15










  • @CarlosHeuberger My "preferred" solution would have the values with both date and times in a single timezone, so you don't end up with to much weirdness, but, it could still be physically possible to arrive before you left even in that scenario. What I'm "trying" to do is get people to "stop" performing mathematic manipulation of date/time values, as that's even worse (IMO)
    – MadProgrammer
    Nov 12 '18 at 8:33










  • I will look into implementing this with my program when it is finished, for now I need to focus on finishing it. Thank you so much for this!
    – Naeem Khan
    Nov 14 '18 at 10:26















2














The primary issue at hand is LocalTime is only a representation of time between midnight AM to midnight PM, it has no concept of any range beyond those bounds.



What you really need is a date value, associated with the time value, this would then allow you to calculate durations beyond a 24 hour period.



Failing that, you will need to "fudge" the values yourself. This means, that when the next time is less than previous time, you will need to manually add an additional period, maybe a day.



There are probably a few ways to do this, this is just one.



It takes a ZonedDateTime (set to the current date) and uses it as a "anchor" date. Each Time of the schedule is then applied to this. When it detects that last arrival time is before the next departure time, it adds a day to the values.



import java.time.Duration;
import java.time.LocalTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

public class Test

public static void main(String args)
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("HHmm");

List<Schedule> route = new ArrayList<>(4);
route.add(new Schedule(LocalTime.parse("1139", formatter), LocalTime.parse("1435", formatter)));
route.add(new Schedule(LocalTime.parse("0906", formatter), LocalTime.parse("1937", formatter)));
route.add(new Schedule(LocalTime.parse("0804", formatter), LocalTime.parse("1521", formatter)));

// Anchor time...
ZonedDateTime zdt = ZonedDateTime.now(ZoneId.of("UTC"));
ZonedDateTime lastArrival = null;
Duration totalDuration = Duration.ZERO;
for (Schedule schedule : route)
ZonedDateTime depart = zdt.with(schedule.getDepart());
ZonedDateTime arrive = zdt.with(schedule.getArrive());

if (lastArrival != null)
if (lastArrival.isAfter(depart))
// Most likely, we've shifted to a new day...
// Updat the anchor and target values
zdt = zdt.plusDays(1);
depart = depart.plusDays(1);
arrive = arrive.plusDays(1);

Duration duration = Duration.between(lastArrival, depart);
totalDuration = totalDuration.plus(duration);
System.out.println("...Wait for " + duration.toHoursPart() + "h " + duration.toMinutesPart() + "m");


Duration duration = Duration.between(depart, arrive);
System.out.println(duration.toHoursPart() + "h " + duration.toMinutesPart() + "m");
totalDuration = totalDuration.plus(duration);

lastArrival = arrive;

System.out.println("Total duration of " + totalDuration.toHoursPart() + "d " + totalDuration.toHoursPart() + "h " + totalDuration.toMinutesPart() + "m");



public static class Schedule

private LocalTime depart;
private LocalTime arrive;

public Schedule(LocalTime depart, LocalTime arrive)
this.depart = depart;
this.arrive = arrive;


public LocalTime getDepart()
return depart;


public LocalTime getArrive()
return arrive;






Which will output...



2h 56m
...Wait for 18h 31m
10h 31m
...Wait for 12h 27m
7h 17m
Total duration of 3d 3h 42m


But why do this? Because date/time manipulation is a complete mess, with leap seconds, years and other stupid rules which are meant to stop it from all falling apart into chaos (this is why there are no flights at 12:00 :/) ... and don't get me started on daylight savings...



The Java date/time API takes care of all of this for us.



I've chosen to maintain the date/time information in a single unit of work, ie UTC, which allows all the values to have some kind of useful meaning. You could easily use a different anchor time as well as convert to a different time zone for use in presentation - so you could display the times in local time at the destination, but the calculations would continue to be done against a single point of truth.






share|improve this answer






















  • to be picky, the primary issue is, IMHO, that we have no date information in the input data - logically, assuming normal flights, if the arrival time is before the departure one, we can assume it must be one day later... but if it is a ship travel, it could be a couple of days later...(most flight plans I know of have something like a +1 to indicate it is the next day)
    – Carlos Heuberger
    Nov 12 '18 at 8:15










  • @CarlosHeuberger My "preferred" solution would have the values with both date and times in a single timezone, so you don't end up with to much weirdness, but, it could still be physically possible to arrive before you left even in that scenario. What I'm "trying" to do is get people to "stop" performing mathematic manipulation of date/time values, as that's even worse (IMO)
    – MadProgrammer
    Nov 12 '18 at 8:33










  • I will look into implementing this with my program when it is finished, for now I need to focus on finishing it. Thank you so much for this!
    – Naeem Khan
    Nov 14 '18 at 10:26













2












2








2






The primary issue at hand is LocalTime is only a representation of time between midnight AM to midnight PM, it has no concept of any range beyond those bounds.



What you really need is a date value, associated with the time value, this would then allow you to calculate durations beyond a 24 hour period.



Failing that, you will need to "fudge" the values yourself. This means, that when the next time is less than previous time, you will need to manually add an additional period, maybe a day.



There are probably a few ways to do this, this is just one.



It takes a ZonedDateTime (set to the current date) and uses it as a "anchor" date. Each Time of the schedule is then applied to this. When it detects that last arrival time is before the next departure time, it adds a day to the values.



import java.time.Duration;
import java.time.LocalTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

public class Test

public static void main(String args)
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("HHmm");

List<Schedule> route = new ArrayList<>(4);
route.add(new Schedule(LocalTime.parse("1139", formatter), LocalTime.parse("1435", formatter)));
route.add(new Schedule(LocalTime.parse("0906", formatter), LocalTime.parse("1937", formatter)));
route.add(new Schedule(LocalTime.parse("0804", formatter), LocalTime.parse("1521", formatter)));

// Anchor time...
ZonedDateTime zdt = ZonedDateTime.now(ZoneId.of("UTC"));
ZonedDateTime lastArrival = null;
Duration totalDuration = Duration.ZERO;
for (Schedule schedule : route)
ZonedDateTime depart = zdt.with(schedule.getDepart());
ZonedDateTime arrive = zdt.with(schedule.getArrive());

if (lastArrival != null)
if (lastArrival.isAfter(depart))
// Most likely, we've shifted to a new day...
// Updat the anchor and target values
zdt = zdt.plusDays(1);
depart = depart.plusDays(1);
arrive = arrive.plusDays(1);

Duration duration = Duration.between(lastArrival, depart);
totalDuration = totalDuration.plus(duration);
System.out.println("...Wait for " + duration.toHoursPart() + "h " + duration.toMinutesPart() + "m");


Duration duration = Duration.between(depart, arrive);
System.out.println(duration.toHoursPart() + "h " + duration.toMinutesPart() + "m");
totalDuration = totalDuration.plus(duration);

lastArrival = arrive;

System.out.println("Total duration of " + totalDuration.toHoursPart() + "d " + totalDuration.toHoursPart() + "h " + totalDuration.toMinutesPart() + "m");



public static class Schedule

private LocalTime depart;
private LocalTime arrive;

public Schedule(LocalTime depart, LocalTime arrive)
this.depart = depart;
this.arrive = arrive;


public LocalTime getDepart()
return depart;


public LocalTime getArrive()
return arrive;






Which will output...



2h 56m
...Wait for 18h 31m
10h 31m
...Wait for 12h 27m
7h 17m
Total duration of 3d 3h 42m


But why do this? Because date/time manipulation is a complete mess, with leap seconds, years and other stupid rules which are meant to stop it from all falling apart into chaos (this is why there are no flights at 12:00 :/) ... and don't get me started on daylight savings...



The Java date/time API takes care of all of this for us.



I've chosen to maintain the date/time information in a single unit of work, ie UTC, which allows all the values to have some kind of useful meaning. You could easily use a different anchor time as well as convert to a different time zone for use in presentation - so you could display the times in local time at the destination, but the calculations would continue to be done against a single point of truth.






share|improve this answer














The primary issue at hand is LocalTime is only a representation of time between midnight AM to midnight PM, it has no concept of any range beyond those bounds.



What you really need is a date value, associated with the time value, this would then allow you to calculate durations beyond a 24 hour period.



Failing that, you will need to "fudge" the values yourself. This means, that when the next time is less than previous time, you will need to manually add an additional period, maybe a day.



There are probably a few ways to do this, this is just one.



It takes a ZonedDateTime (set to the current date) and uses it as a "anchor" date. Each Time of the schedule is then applied to this. When it detects that last arrival time is before the next departure time, it adds a day to the values.



import java.time.Duration;
import java.time.LocalTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

public class Test

public static void main(String args)
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("HHmm");

List<Schedule> route = new ArrayList<>(4);
route.add(new Schedule(LocalTime.parse("1139", formatter), LocalTime.parse("1435", formatter)));
route.add(new Schedule(LocalTime.parse("0906", formatter), LocalTime.parse("1937", formatter)));
route.add(new Schedule(LocalTime.parse("0804", formatter), LocalTime.parse("1521", formatter)));

// Anchor time...
ZonedDateTime zdt = ZonedDateTime.now(ZoneId.of("UTC"));
ZonedDateTime lastArrival = null;
Duration totalDuration = Duration.ZERO;
for (Schedule schedule : route)
ZonedDateTime depart = zdt.with(schedule.getDepart());
ZonedDateTime arrive = zdt.with(schedule.getArrive());

if (lastArrival != null)
if (lastArrival.isAfter(depart))
// Most likely, we've shifted to a new day...
// Updat the anchor and target values
zdt = zdt.plusDays(1);
depart = depart.plusDays(1);
arrive = arrive.plusDays(1);

Duration duration = Duration.between(lastArrival, depart);
totalDuration = totalDuration.plus(duration);
System.out.println("...Wait for " + duration.toHoursPart() + "h " + duration.toMinutesPart() + "m");


Duration duration = Duration.between(depart, arrive);
System.out.println(duration.toHoursPart() + "h " + duration.toMinutesPart() + "m");
totalDuration = totalDuration.plus(duration);

lastArrival = arrive;

System.out.println("Total duration of " + totalDuration.toHoursPart() + "d " + totalDuration.toHoursPart() + "h " + totalDuration.toMinutesPart() + "m");



public static class Schedule

private LocalTime depart;
private LocalTime arrive;

public Schedule(LocalTime depart, LocalTime arrive)
this.depart = depart;
this.arrive = arrive;


public LocalTime getDepart()
return depart;


public LocalTime getArrive()
return arrive;






Which will output...



2h 56m
...Wait for 18h 31m
10h 31m
...Wait for 12h 27m
7h 17m
Total duration of 3d 3h 42m


But why do this? Because date/time manipulation is a complete mess, with leap seconds, years and other stupid rules which are meant to stop it from all falling apart into chaos (this is why there are no flights at 12:00 :/) ... and don't get me started on daylight savings...



The Java date/time API takes care of all of this for us.



I've chosen to maintain the date/time information in a single unit of work, ie UTC, which allows all the values to have some kind of useful meaning. You could easily use a different anchor time as well as convert to a different time zone for use in presentation - so you could display the times in local time at the destination, but the calculations would continue to be done against a single point of truth.







share|improve this answer














share|improve this answer



share|improve this answer








edited Nov 12 '18 at 7:56

























answered Nov 12 '18 at 1:44









MadProgrammer

299k17153265




299k17153265











  • to be picky, the primary issue is, IMHO, that we have no date information in the input data - logically, assuming normal flights, if the arrival time is before the departure one, we can assume it must be one day later... but if it is a ship travel, it could be a couple of days later...(most flight plans I know of have something like a +1 to indicate it is the next day)
    – Carlos Heuberger
    Nov 12 '18 at 8:15










  • @CarlosHeuberger My "preferred" solution would have the values with both date and times in a single timezone, so you don't end up with to much weirdness, but, it could still be physically possible to arrive before you left even in that scenario. What I'm "trying" to do is get people to "stop" performing mathematic manipulation of date/time values, as that's even worse (IMO)
    – MadProgrammer
    Nov 12 '18 at 8:33










  • I will look into implementing this with my program when it is finished, for now I need to focus on finishing it. Thank you so much for this!
    – Naeem Khan
    Nov 14 '18 at 10:26
















  • to be picky, the primary issue is, IMHO, that we have no date information in the input data - logically, assuming normal flights, if the arrival time is before the departure one, we can assume it must be one day later... but if it is a ship travel, it could be a couple of days later...(most flight plans I know of have something like a +1 to indicate it is the next day)
    – Carlos Heuberger
    Nov 12 '18 at 8:15










  • @CarlosHeuberger My "preferred" solution would have the values with both date and times in a single timezone, so you don't end up with to much weirdness, but, it could still be physically possible to arrive before you left even in that scenario. What I'm "trying" to do is get people to "stop" performing mathematic manipulation of date/time values, as that's even worse (IMO)
    – MadProgrammer
    Nov 12 '18 at 8:33










  • I will look into implementing this with my program when it is finished, for now I need to focus on finishing it. Thank you so much for this!
    – Naeem Khan
    Nov 14 '18 at 10:26















to be picky, the primary issue is, IMHO, that we have no date information in the input data - logically, assuming normal flights, if the arrival time is before the departure one, we can assume it must be one day later... but if it is a ship travel, it could be a couple of days later...(most flight plans I know of have something like a +1 to indicate it is the next day)
– Carlos Heuberger
Nov 12 '18 at 8:15




to be picky, the primary issue is, IMHO, that we have no date information in the input data - logically, assuming normal flights, if the arrival time is before the departure one, we can assume it must be one day later... but if it is a ship travel, it could be a couple of days later...(most flight plans I know of have something like a +1 to indicate it is the next day)
– Carlos Heuberger
Nov 12 '18 at 8:15












@CarlosHeuberger My "preferred" solution would have the values with both date and times in a single timezone, so you don't end up with to much weirdness, but, it could still be physically possible to arrive before you left even in that scenario. What I'm "trying" to do is get people to "stop" performing mathematic manipulation of date/time values, as that's even worse (IMO)
– MadProgrammer
Nov 12 '18 at 8:33




@CarlosHeuberger My "preferred" solution would have the values with both date and times in a single timezone, so you don't end up with to much weirdness, but, it could still be physically possible to arrive before you left even in that scenario. What I'm "trying" to do is get people to "stop" performing mathematic manipulation of date/time values, as that's even worse (IMO)
– MadProgrammer
Nov 12 '18 at 8:33












I will look into implementing this with my program when it is finished, for now I need to focus on finishing it. Thank you so much for this!
– Naeem Khan
Nov 14 '18 at 10:26




I will look into implementing this with my program when it is finished, for now I need to focus on finishing it. Thank you so much for this!
– Naeem Khan
Nov 14 '18 at 10:26

















draft saved

draft discarded
















































Thanks for contributing an answer to Stack Overflow!


  • Please be sure to answer the question. Provide details and share your research!

But avoid


  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.





Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


Please pay close attention to the following guidance:


  • Please be sure to answer the question. Provide details and share your research!

But avoid


  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53254475%2flocaltime-difference-between-two-times%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

Use pre created SQLite database for Android project in kotlin

Darth Vader #20

Ondo