Skip to content

Snappy1

  • Home
  • Android
  • What
  • How
  • Is
  • Can
  • Does
  • Do
  • Why
  • Are
  • Who
  • Toggle search form

[FIXED] java – Trying to take two timestamps, subtract them, convert the difference to seconds and store in an int variable

Posted on November 11, 2022 By

Solution 1 :

Are you using Java 8?

If so you could convert to Instants and get the Duration between them:

    Calendar cal = ...
    Calendar cal2 = ...
    Instant instantOne = cal.toInstant();
    Instant instanceTwo = cal2.toInstant();
    Duration between = Duration.between(instantOne, instanceTwo);
    long seconds = between.getSeconds();

I assumed there was a reason you’re using Calendar to begin with (it passed to you without your control?) … If not then you can just use Instant.now() from the get go and cut out pre Java 8 date/time classes

Solution 2 :

The good answer by tomgeraghty3 may be all that you need. I am contributing a supplement.

java.time and ThreeTenABP

If I understood correctly, you really had two requirements:

  1. You need to be able to represent the start and end times in HH:mm:ss format.
  2. You need the elapsed time between start and end in seconds.

Don’t represent your times as strings, though. Doing calculations on those is pretty hopeless. Represent your times by proper date-time objects. Only format into strings when you need to give string output.

    DateTimeFormatter timeFormatter = DateTimeFormatter.ofPattern("HH:mm:ss");

    ZonedDateTime start = ZonedDateTime.now(ZoneId.systemDefault());
    TimeUnit.SECONDS.sleep(175); // Simulate that time passes
    ZonedDateTime end = ZonedDateTime.now(ZoneId.systemDefault());

    long diffSeconds = ChronoUnit.SECONDS.between(start, end);

    System.out.printf("From %s until %s was %d seconds",
            start.format(timeFormatter), end.format(timeFormatter), diffSeconds);

Example run:

From 05:49:41 until 05:52:36 was 175 seconds

Of course to see it run, stick in a smaller number like 3 or 6 instead of 175 first.

If printing HH:mm:ss format was not a requirement, you may use Instant instead of ZonedDateTime as in the answer by tomgeraghty3. Since in Instant is independent of time zone you would then leave out the argument to the now method:

    Instant start = Instant.now();

Similarly for end.

Depending on the work you need to do on the value you may want to consider the Duration class to represent the difference rather then a simple count of seconds. This too is demonstrated in the answer by tomgeraghty3.

READ  [FIXED] android - Relaunch specific activity from middle of the stack again by closing all activities above (including specific one)
Powered by Inline Related Posts

Question: Doesn’t java.time require Android API level 26?

java.time works nicely on both older and newer Android devices. It just requires at least Java 6.

  • In Java 8 and later and on newer Android devices (from API level 26) the modern API comes built-in.
  • In non-Android Java 6 and 7 get the ThreeTen Backport, the backport of the modern classes (ThreeTen for JSR 310; see the links at the bottom).
  • On (older) Android use the Android edition of ThreeTen Backport. It’s called ThreeTenABP. And make sure you import the date and time classes from org.threeten.bp with subpackages.

Links

  • Documentation of the Duration class
  • Oracle tutorial: Date Time explaining how to use java.time.
  • Java Specification Request (JSR) 310, where java.time was first described.
  • ThreeTen Backport project, the backport of java.time to Java 6 and 7 (ThreeTen for JSR-310).
  • ThreeTenABP, Android edition of ThreeTen Backport
  • Question: How to use ThreeTenABP in Android Project, with a very thorough explanation.

Solution 3 :

Here’s one way you can easily do it using LocalDateTime.

LocalDateTime instance1 = LocalDateTime.now();
//Do stuff
LocalDateTime instance2 = LocalDateTime.now();
long elapsedTimeInSeconds = instance1.until(instance2, ChronoUnit.SECONDS);
System.out.println(elapsedTimeInSeconds);

Since you already have a timestamp, assuming it’s in the form of a String you can convert it to a LocalDateTime like so:

String timestamp = "2012-08-15T22:56:02.038Z";
LocalDateTime instance = LocalDateTime.ofInstant(Instant.parse(timestamp), ZoneId.systemDefault());

Edit: Changed LocalTime to LocalDateTime to fix rollover issues with previous solution.

Problem :

I’m having trouble understanding getting timestamps, subtracting them, and being able to assign and use the difference in future calculations. I am using Java in Android Studio.

When I use SimpleDateFormat and Calendar, I’m able to get the current time in HH:mm:ss but I’m not sure how to subtract two of those timestamps from each other and convert the difference into seconds. My end goal is to take the difference, convert it into seconds, assign it to an int, and later compare the value to other, predetermined values. This is a project in Android Studio so I have buttons already set up to fetch the timestamps.

READ  [FIXED] android - Could not find fragment.jar (androidx.fragment:fragment:1.0.0)
Powered by Inline Related Posts

Example:
– Get a current timestamp, say 16:50:32
– Get a second timestamp in the near future, say 16:53:29 (roughly three minutes later)
– Subtract those two timestamps and store the value in seconds, so the final value would be 177 (seconds)
– have this value of 177 in a variable so that I can do more things with it.

I’m able to use the following code to get the timestamps

Calendar calendar = Calendar.getInstance();
SimpleDateFormat startTime = new SimpleDateFormat("HH:mm:ss");
timeTest = startTime.format(calendar.getTime());

SimpleDateFormat endTime = new SimpleDateFormat("HH:mm:ss");
timeTest2 = endTime.format(calendar.getTime());

But after getting two timestamps I do not know how to subtract them, convert them to seconds and store them in an int value.

Comments

Comment posted by Hawk

Maybe you could use

Comment posted by ThreeTenABP

As an aside consider throwing away the long outmoded and notoriously troublesome

Comment posted by How do I ask a good question?

Please take a look into our help center for tips on increasing your chances of good answers. The first thing it says is:

Comment posted by In Java, how do I get the difference in seconds between 2 dates?

Does this answer your question?

Comment posted by Ole V.V.

While

Comment posted by Tim Hunter

@OleV.V. Fair enough, mate.

Comment posted by Tim Hunter

@OleV.V. Thinking about it,

Android Tags:android, java, timestamp

Post navigation

Previous Post: [FIXED] java – MVVM with Room and LiveData – How to get List from LiveData
Next Post: [FIXED] android – Xamarin.Forms.Droid Resource, Ambiguous Terms/ Build Action’s Randomly Changing Missing Resources

Related Posts

[FIXED] android – failed to publish release on play store: ERROR: dump failed because no AndroidManifest.xml found Android
[FIXED] Android Studio does not recognize my phone as an android, but adb sees it Android
[FIXED] java – Adding multiple items to a listview with each item received from another intent on a button click Android
[FIXED] Flutter error on building files in Android Studio Android
[FIXED] reactjs – Splash Screen quickly turns to white on React Native Android Android
[FIXED] flutter – Error starting build – Android build failing on App Center Android

Archives

  • March 2023
  • February 2023
  • January 2023
  • December 2022
  • November 2022
  • October 2022
  • September 2022

Categories

  • ¿Cómo
  • ¿Cuál
  • ¿Cuándo
  • ¿Cuántas
  • ¿Cuánto
  • ¿Qué
  • Android
  • Are
  • At
  • C'est
  • Can
  • Comment
  • Did
  • Do
  • Does
  • Est-ce
  • Est-il
  • For
  • Has
  • Hat
  • How
  • In
  • Is
  • Ist
  • Kann
  • Où
  • Pourquoi
  • Quand
  • Quel
  • Quelle
  • Quelles
  • Quels
  • Qui
  • Should
  • Sind
  • Sollte
  • Uncategorized
  • Wann
  • Warum
  • Was
  • Welche
  • Welchen
  • Welcher
  • Welches
  • Were
  • What
  • What's
  • When
  • Where
  • Which
  • Who
  • Who's
  • Why
  • Wie
  • Will
  • Wird
  • Wo
  • Woher
  • you can create a selvedge edge: You can make the edges of garter stitch more smooth by slipping the first stitch of every row.2022-02-04
  • you really only need to know two patterns: garter stitch

Recent Posts

  • What color are dead flea eggs?
  • What is Indiana vine?
  • What’s the downside of a Chromebook?
  • Is phosphide the same as phosphorus?
  • Why do you need an S bend?

Recent Comments

No comments to show.

Copyright © 2023 Snappy1.

Powered by PressBook Grid Dark theme