Skip to content

Instantly share code, notes, and snippets.

@hendrawd
Created November 12, 2015 05:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hendrawd/588251f0f97552846335 to your computer and use it in GitHub Desktop.
Save hendrawd/588251f0f97552846335 to your computer and use it in GitHub Desktop.
A Java class with a method that can return relative time span string with Indonesian language(bahasa)
package com;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;
import java.util.concurrent.TimeUnit;
/**
* Created by hendrawd on 11/12/15.
*/
public class TimeUtil {
/**
* @param time String time, format = "dd-MM-yyyy HH:mm:ss"
* @return String relative time span with Indonesian language(bahasa)
*/
public static String getRelativeTimeSpanString(String time) {
try {
//set the format of the input time
SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss", Locale.ENGLISH);
//set the timezone of the input time
sdf.setTimeZone(TimeZone.getTimeZone("GMT+7"));
Date datePast = sdf.parse(time);
Date dateNow = new Date();
//set the strings that will be used
String sAgo = "yang lalu";
String sMilli = "mili detik";
String sSecond = "detik";
String sMinute = "menit";
String sHour = "jam";
String sDay = "hari";
String sWeek = "minggu";
String sMonth = "bulan";
String sYear = "tahun";
long lDay = TimeUnit.MILLISECONDS.toDays(dateNow.getTime() - datePast.getTime());
if (lDay == 0) {
long lHour = TimeUnit.MILLISECONDS.toHours(dateNow.getTime() - datePast.getTime());
if (lHour == 0) {
long lMinute = TimeUnit.MILLISECONDS.toMinutes(dateNow.getTime() - datePast.getTime());
if (lMinute == 0) {
long lSecond = TimeUnit.MILLISECONDS.toSeconds(dateNow.getTime() - datePast.getTime());
if (lSecond == 0) {
long lMilliSecond = TimeUnit.MILLISECONDS.toMillis(dateNow.getTime() - datePast.getTime());
if (lMilliSecond == 0) {
//this will be happen if the time is in the future
return time;
} else {
return lMilliSecond + " " + sMilli + " " + sAgo;
}
} else {
return lSecond + " " + sSecond + " " + sAgo;
}
} else {
return lMinute + " " + sMinute + " " + sAgo;
}
} else {
return lHour + " " + sHour + " " + sAgo;
}
} else {
if (lDay < 7) {
return lDay + " " + sDay + " " + sAgo;
} else {
long lWeek = lDay / 7;
if (lWeek < 4) {
return lWeek + " " + sWeek + " " + sAgo;
} else if (lWeek == 4) {
return 1 + sMonth + " " + sAgo;
} else {
long lMonth = lDay / 30;
if (lMonth < 12) {
return lMonth + " " + sMonth + " " + sAgo;
} else if (lMonth == 12) {
return 1 + sYear + " " + sAgo;
} else {
long lYear = lDay / 365;
return lYear + " " + sYear + " " + sAgo;
}
}
}
}
} catch (Exception e) {
return time;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment