Asked  7 Months ago    Answers:  5   Viewed   26 times

I want to calculate difference between 2 dates in hours/minutes/seconds.

I have a slight problem with my code here it is :

String dateStart = "11/03/14 09:29:58";
String dateStop = "11/03/14 09:33:43";

// Custom date format
SimpleDateFormat format = new SimpleDateFormat("yy/MM/dd HH:mm:ss");  

Date d1 = null;
Date d2 = null;
try {
    d1 = format.parse(dateStart);
    d2 = format.parse(dateStop);
} catch (ParseException e) {
    e.printStackTrace();
}    

// Get msec from each, and subtract.
long diff = d2.getTime() - d1.getTime();
long diffSeconds = diff / 1000;         
long diffMinutes = diff / (60 * 1000);         
long diffHours = diff / (60 * 60 * 1000);                      
System.out.println("Time in seconds: " + diffSeconds + " seconds.");         
System.out.println("Time in minutes: " + diffMinutes + " minutes.");         
System.out.println("Time in hours: " + diffHours + " hours."); 

This should produce :

Time in seconds: 45 seconds.
Time in minutes: 3 minutes.
Time in hours: 0 hours.

However I get this result :

Time in seconds: 225 seconds.
Time in minutes: 3 minutes.
Time in hours: 0 hours.

Can anyone see what I'm doing wrong here ?

 Answers

10

try

long diffSeconds = diff / 1000 % 60;  
long diffMinutes = diff / (60 * 1000) % 60; 
long diffHours = diff / (60 * 60 * 1000);

NOTE: this assumes that diff is non-negative.

Tuesday, June 1, 2021
 
nasty
answered 7 Months ago
91

I changed my computer’s time zone to Europe/Bucharest for an experiment. This is UTC + 2 hours like your time zone.

Now when I copy your code I get a result similar to yours:

    Instant now = Instant.now();
    System.out.println(now); // prints 2017-03-14T06:16:32.621Z
    Timestamp current = Timestamp.from(now);
    System.out.println(current); // 2017-03-14 08:16:32.621

Output is given in comments. However, I go on:

    DateFormat df = DateFormat.getDateTimeInstance();
    df.setTimeZone(TimeZone.getTimeZone("UTC"));
    // the following prints: Timestamp in UTC: 14-03-2017 06:16:32
    System.out.println("Timestamp in UTC: " + df.format(current));

Now you can see that the Timestamp really agrees with the Instant we started out from (only the milliseconds are not printed, but I trust they are in there too). So you have done everything correctly and only got confused because when we printed the Timestamp we were implicitly calling its toString method, and this method in turn grabs the computer’s time zone setting and displays the time in this zone. Only because of this, the displays are different.

The other thing you attempted, using LocalDateTime, appears to work, but it really does not give you what you want:

    LocalDateTime ldt = LocalDateTime.ofInstant(Instant.now(), ZoneOffset.UTC);
    System.out.println(ldt); // 2017-03-14T06:16:32.819
    current = Timestamp.valueOf(ldt);
    System.out.println(current); // 2017-03-14 06:16:32.819
    System.out.println("Timestamp in UTC: " + df.format(current)); // 14-03-2017 04:16:32

Now when we print the Timestamp using our UTC DateFormat, we can see that it is 2 hours too early, 04:16:32 UTC when the Instant is 06:16:32 UTC. So this method is deceiving, it looks like it’s working, but it doesn’t.

This shows the trouble that lead to the design of the Java 8 date and time classes to replace the old ones. So the real and good solution to your problem would probably be to get yourself a JDBC 4.2 driver that can accept an Instant object readily so you can avoid converting to Timestamp altogether. I don’t know if that’s available for you just yet, but I’m convinced it will be.

Wednesday, June 16, 2021
 
DMTintner
answered 6 Months ago
15

If you use the GregorianCalendar, you could do as below

Determines if the given year is a leap year. Returns true if the given year is a leap year. To specify BC year numbers, 1 - year number must be given. For example, year BC 4 is specified as -3.

GregorianCalendar cal = new GregorianCalendar();

if(cal.isLeapYear(year))
{
    System.out.print("Given year is leap year.");
}
else
{ 
    System.out.print("Given year is not leap year.");
}
Wednesday, August 4, 2021
 
LOKESH
answered 4 Months ago
61

So the 1st question I have is. Since this "tab" is running on a separate controller but is included into the main program, does it run on a separate application thread?

No, there can only be one JavaFX Application instance per JVM, and also one JavaFX Application Thread per JVM.

As for how you could update the timer, it is fine to use Timeline - one for each timer. Timeline does not run on separate thread - it is triggered by the underlying "scene graph rendering pulse" which is responsible for updating the JavaFX GUI periodically. Having more Timeline instances basically just means that there are more listeners that subscribes to the "pulse" event.

public class TimerController {
    private final Timeline timer;

    private final ObjectProperty<java.time.Duration> timeLeft;

    @FXML private Label timeLabel;

    public TimerController() {
        timer = new Timeline();
        timer.getKeyFrames().add(new KeyFrame(Duration.seconds(1), ae -> updateTimer()));
        timer.setCycleCount(Timeline.INDEFINITE);

        timeLeft = new SimpleObjectProperty<>();
    }
    public void initialize() {
        timeLabel.textProperty().bind(Bindings.createStringBinding(() -> getTimeStringFromDuration(timeLeft.get()), timeLeft));
    }

    @FXML
    private void startTimer(ActionEvent ae) {
        timeLeft.set(Duration.ofMinutes(5)); // For example timer of 5 minutes
        timer.playFromStart();
    }

    private void updateTimer() {
        timeLeft.set(timeLeft.get().minusSeconds(1));
    }

    private static String getTimeStringFromDuration(Duration duration) {
        // Do the conversion here...
    }
}

Of course, you can also use Executor and other threading methods, provided you update the Label via Platform.runLater(). Alternatively, you could use a Task.

This is a general example when using background thread:

final Duration countdownDuration = Duration.ofSeconds(5);
Thread timer = new Thread(() -> {
    LocalTime start = LocalTime.now();
    LocalTime current = LocalTime.now();
    LocalTime end = start.plus(countDownDuration);

    while (end.isAfter(current)) {
        current = LocalTime.now();
        final Duration elapsed = Duration.between(current, end);

        Platform.runLater(() -> timeLeft.set(current)); // As the label is bound to timeLeft, this line must be inside Platform.runLater()
        Thread.sleep(1000);
    }
});
Tuesday, August 31, 2021
 
Navaneeth K N
answered 3 Months ago
89

This is an alternate code for the above which will give you 41957.

var date1 = new Date("1/1/1900");
var date2 = new Date("11/16/2014");
var timeDiff = Math.abs(date2.getTime() - date1.getTime());
var diffDays = Math.ceil(timeDiff / (1000 * 3600 * 24)); 
alert(diffDays);

Reference : Get difference between 2 dates in javascript?

Wednesday, October 20, 2021
 
test12345
answered 2 Months ago
Only authorized users can answer the question. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :  
Share