Skip to content

Instantly share code, notes, and snippets.

@Talon876
Created September 5, 2015 16:31
Show Gist options
  • Save Talon876/0757a3cd760fe3096918 to your computer and use it in GitHub Desktop.
Save Talon876/0757a3cd760fe3096918 to your computer and use it in GitHub Desktop.
package time;
import java.util.HashMap;
import java.util.Map;
public class TimeConverter {
private HashMap<String, Integer> timeMappings = new HashMap<>();
public TimeConverter() {
timeMappings.put("second", 1);
timeMappings.put("minute", 60);
timeMappings.put("hour", 3600);
timeMappings.put("day", 86400);
timeMappings.put("week", 604800);
//add as many units as you want
}
public int unitToSeconds(String unit) {
int result = -1;
if (timeMappings.containsKey(unit)) {
result = timeMappings.get(unit);
}
return result;
}
public String secondsToUnit(int seconds) {
String result = "no match";
for(Map.Entry<String, Integer> entry : timeMappings.entrySet()) {
if(entry.getValue() == seconds) {
result = entry.getKey();
}
}
return result;
}
public static void main(String[] args) {
TimeConverter t = new TimeConverter();
System.out.println(t.secondsToUnit(60));
System.out.println(t.secondsToUnit(604800));
System.out.println(t.secondsToUnit(999));
System.out.println(t.unitToSeconds("second"));
System.out.println(t.unitToSeconds("hour"));
System.out.println(t.unitToSeconds("henway"));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment