Last active
October 21, 2019 13:39
-
-
Save AndresGarciaSobrado91/32f7b84b902f704cb3a30ac947116d17 to your computer and use it in GitHub Desktop.
Util to get the elapsed (relative) time from a given date to now. Currently supports English & Spanish
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.ArrayList; | |
import java.util.Arrays; | |
import java.util.Date; | |
import java.util.List; | |
public class ElapsedTimeUtil { | |
Date now, date; | |
List<String> englishStrings = Arrays.asList("Moments ago", "1 day ago", "1 week ago", " days ago", "1 year ago", " years ago", "1 month ago", " months ago"); | |
List<String> spanishStrings = Arrays.asList("Hace algunos momentos", "Hace 1 día", "Hace 1 semana", " días atrás", "Hace más de 1 año", " años atrás", "Hace más de 1 mes", " meses atrás"); | |
public enum Language{ | |
SPANISH, ENGLISH | |
} | |
public ElapsedTimeUtil(Date date) { | |
this.now = new Date(); | |
this.date = date; | |
} | |
public void setDate(Date date) { | |
this.date = date; | |
} | |
public String getElapsedTime(Language language){ | |
List<String> languageStrings = new ArrayList<>(); | |
switch (language){ | |
case SPANISH: | |
languageStrings = this.spanishStrings; | |
break; | |
case ENGLISH: | |
languageStrings = this.englishStrings; | |
break; | |
} | |
long nowInLong = this.now.getTime(); | |
long dateInLong = this.date.getTime(); | |
long diff = nowInLong - dateInLong; | |
long diffInDays = diff / (1000L * 60L * 60L * 24L); | |
if (diffInDays == 0){ | |
return languageStrings.get(0); | |
} | |
if (diffInDays == 1){ | |
return languageStrings.get(1); | |
} | |
if (diffInDays == 7){ | |
return languageStrings.get(2); | |
} | |
if (diffInDays < 30){ | |
return diffInDays + languageStrings.get(3); | |
} else { | |
if (diffInDays >= 365){ | |
long diffInYears = diff / (1000L * 60L * 60L * 24L * 31L * 12L); | |
if (diffInYears == 1){ | |
return languageStrings.get(4); | |
} else { | |
return diffInYears + languageStrings.get(5); | |
} | |
} | |
long diffInMonths = diff / (1000L * 60L * 60L * 24L * 30L); | |
if (diffInMonths == 1){ | |
return languageStrings.get(6); | |
} else { | |
return diffInMonths + languageStrings.get(7); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Example:
