-1

What I'm trying to do: Check for the minutes until an event. (I'm in central time which is UTC -5 hours). The object I get is a JSON Element that looks like this when I take the string:

/Date(1502964420000-0500)/

I should be able to:

//take the departure time and subtract it from the current time. Divide by 60
    timeStamp = timeStamp.substring(6,16);

This gives me 1502964420 which I can use a time converter to get: Thursday, August 17, 2017 5:07:00 AM

Problem is.. How do I get the current time in the same format to subtract it? (or if there's a better way to do this I'd gladly take that advice as well).

Runesr4nerds
  • 19
  • 1
  • 3
  • 1502964420 seems to me to be seconds since the epoch. How do you get the current time in the same format? I recommend [this answer](https://stackoverflow.com/a/43687687/5772882). – Ole V.V. Aug 17 '17 at 17:42
  • Possible duplicate of [how to find seconds since 1970 in java](https://stackoverflow.com/questions/8263148/how-to-find-seconds-since-1970-in-java) – Ole V.V. Aug 17 '17 at 17:43

2 Answers2

1

I would recommend looking at the datatype ZonedDateTime.

With this you can easily perform calculasions and conversions like this:

ZonedDateTime startTime = ZonedDateTime.now();
Instant timestamp = startTime.toInstant(); // You can also convert to timestamp
ZonedDateTime endTime = startTime.plusSeconds(30);

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

if(duration.isNegative()){
  // The end is before the start
}

long secondsBetween = duration.toMillis(); // duration between to seconds

Since you don't know about ZonedDateTime here is a quick overview how to convert string to ZonedDateTime:

Note: The String has to be in the ISO8601 format!

String example = "2017-08-17T09:14+02:00";
OffsetDateTime offset = OffsetDateTime.parse(example);
ZonedDateTime result = offset.atZoneSameInstant( ZoneId.systemDefault() );
Nico
  • 1,727
  • 1
  • 24
  • 42
0

You can either use Date currentDate = new Date() and then currentDate.getTime() to get the current Unix time in milliseconds or use the Calendar-class: Calendar currentDate = Calendar.getInstance() and currentDate.getTime().getTime() to get the current Unix time in milliseconds.

You can do the same with the date parsed from the json and then calculate the difference between the two values. To get the difference in minutes, just divide it then by (60*1000)

vatbub
  • 2,713
  • 18
  • 41
  • The idea is right, Please don’t teach the young ones to use the long outdated classes `Date` and `Calendar`. Today we have so much better. I recommend the `Instant` class instead. – Ole V.V. Aug 17 '17 at 17:45