CodeZero CodeZero - 17 days ago 5
Android Question

Converting "time ago" to seconds in android

I have my server returning a time ago string format like this

2 minutes ago
which is fine but I now need to convert it to seconds. I thought of just splitting the string using a space delimiter and getting the first text but then, there are cases of my server returning instances of
5 hour 43 minutes ago
etc. My question is this, Is there a neat way of conversion from this time ago format bearing in mind of these instances to just seconds?

ctu ctu

I dont think there is a particular library or method that can do the conversion from your "time ago" to seconds. The best option for you would be to parse the "Time ago" string returns by your server and do the conversion yourself. The simplest way would be to split your string on space boundaries then get the values of hours and min.

 public static int timeAgoToSeconds(String timeAgo) {
    int timeInSec = 0;
    String []myStringArray = timeAgo.trim().split(" ");

     timeInSec = Integer.valueOf(myStringArray[0]) *60;

        timeInSec = Integer.valueOf(myStringArray[0]) *3600 + Integer.valueOf(myStringArray[2]) * 60; 

 return timeInSec;


test in the main() method:

  String timeAgoHHmm = "5 hour 43 minutes ago";
  String timeAgoMM = "2 minutes ago";