Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;
//to use, copy, modify, merge, publish, distribute, sublicense, and/or sell

import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;

public class Main {
    private static final long TIME_MILLIS = 1000;
    private static final long TIME_MINUTE = 60 * TIME_MILLIS;
    private static final long TIME_HOUR = 60 * TIME_MINUTE;
    private static final long TIME_DAY = 24 * TIME_HOUR;

    public static String convertToHumanReadableTime(Date givenDate, long currentTimeLong) {

        Calendar currentTime = Calendar.getInstance();
        currentTime.setTimeZone(TimeZone.getTimeZone("UTC"));
        currentTime.setTimeInMillis(currentTimeLong);

        Calendar givenTime = Calendar.getInstance();
        givenTime.setTimeZone(TimeZone.getTimeZone("UTC"));
        givenTime.setTime(givenDate);

        // Step 1: To see if time difference is less than 24 hours of not
        long timeDiff = currentTime.getTimeInMillis() - givenTime.getTimeInMillis();
        if (timeDiff <= 0) {
            return "Now";
        }

        String humanString = null;
        // Checking if timeDiff is less than 24 or not
        if ((timeDiff / TIME_DAY) >= 1) {
            // days
            int days = (int) (timeDiff / TIME_DAY);
            humanString = String.format(Locale.getDefault(), "%dd", days);
        } else {
            // checking if greater than hour
            if ((timeDiff / TIME_HOUR) >= 1) {
                humanString = String.format(Locale.getDefault(), "%dh", (timeDiff / TIME_HOUR));
            } else if ((timeDiff / TIME_MINUTE) >= 1) {
                humanString = String.format(Locale.getDefault(), "%dm", (timeDiff / TIME_MINUTE));
            } else {
                humanString = String.format(Locale.getDefault(), "%ds", (timeDiff / TIME_MILLIS));
            }
        }

        return humanString;
    }
}