[F/OS] Date To Time Ago (e.g., 1 min, 2 h, 3 days)

Converts an ISO 8601 date to relative time (e.g., 1 min, 2 h, 3 days).

:puzzle_piece: Function Blocks


Format ISO 8601: yyyy-MM-dd’T’HH:mm:ss.SSSSSS’Z’

Result:


Currently in use in my PolyMaps app.

:memo: Specifications


:package: Package:
com.thiagolowcode.datetoago.aix (4.9 KB)
:date: Updated On: 2026-04-18T00:00:00Z
:package: Version: 1
:laptop: Built using: RUSH

Source Code:

package com.thiagolowcode.datetoago;

import com.google.appinventor.components.annotations.*;
import com.google.appinventor.components.common.ComponentCategory;
import com.google.appinventor.components.runtime.AndroidNonvisibleComponent;
import com.google.appinventor.components.runtime.ComponentContainer;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;

public class DateToTimeAgo extends AndroidNonvisibleComponent {

    public DateToTimeAgo(ComponentContainer container) {
        super(container.$form());
    }

    @SimpleFunction(description = "Converts an ISO 8601 date to relative time (e.g., 1 min, 2 h, 3 days).")
    public String TimeAgo(String isoDate) {

        try {
            SimpleDateFormat sdf = new SimpleDateFormat(
                    "yyyy-MM-dd'T'HH:mm:ss.SSSSSS'Z'",
                    Locale.US
            );
            sdf.setTimeZone(TimeZone.getTimeZone("UTC"));

            Date pastDate = sdf.parse(isoDate);
            long now = System.currentTimeMillis();
            long diff = now - pastDate.getTime();

            long seconds = diff / 1000;
            long minutes = seconds / 60;
            long hours = minutes / 60;
            long days = hours / 24;
            long months = days / 30;
            long years = days / 365;

            if (seconds < 60) {
                return "now";
            } else if (minutes < 60) {
                return minutes + " min";
            } else if (hours < 24) {
                return hours + " h";
            } else if (days < 30) {
                return days + " days";
            } else if (months < 12) {
                return months + " months";
            } else {
                return years + " years";
            }

        } catch (ParseException e) {
            return "Invalid date. Try the format: yyyy-MM-dd'T'HH:mm:ss.SSSSSS'Z'";
        }
    }
}
4 Likes