-1

I have a PHP web service sending JSON responses back to my Java client. and the time returns in JSON like this:

created_at: "2018-04-02 20:06:42"

I'm getting the datetime as a string in my Android application, So I want to show the elapsed time on my Android application based on this string. I tried many ways like converting it to long, double, date objects none of them worked for me. so what's the right way to convert it to a java object that I can mines the current time to get the elapsed time since the date recorded?

user2682025
  • 656
  • 2
  • 13
  • 39

1 Answers1

3

Your input represents a local date/time (2018-04-02 20:06:42), and to get the elapsed time, you need to define which timezone you'll use.

The input corresponds to April 2nd 2018, at 8:06:42 PM, but where? Note that, in different parts of the world, 8 PM occurred in a different moment, depending on what timezone you are. Without knowing the exact timezone that the input refers to, it's impossible to compare it with "now".

If you have some way to figure out what's the timezone that corresponds to the input, then you can start doing something like this:

String input = "2018-04-02 20:06:42";
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
// use the timezone name. Example: "UTC", "America/New_York", "Europe/Berlin", etc
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));

Date date = sdf.parse(input);
// difference in milliseconds
long diffFromNow = System.currentTimeMillis() - date.getTime();

Another alternative (a better one, IMO), is to use java.time (for API level 26), or threeten backport (for API level < 26 - see here how to configure it in Android):

DateTimeFormatter fmt = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
ZonedDateTime zdt = LocalDateTime
    // parse date/time String
    .parse(input, fmt)
    // set to a timezone (for UTC, use ZoneOffset.UTC)
    .atZone(ZoneId.of("America/New_York"));

// difference in milliseconds
long diffFromNow = ChronoUnit.MILLIS.between(Instant.now(), zdt.toInstant());
soupp
  • 46
  • 1