Skip to content

Instantly share code, notes, and snippets.

@ayushhgoyal
Created September 14, 2015 15:46
Show Gist options
  • Save ayushhgoyal/9c07d61614fbe6cef005 to your computer and use it in GitHub Desktop.
Save ayushhgoyal/9c07d61614fbe6cef005 to your computer and use it in GitHub Desktop.
Time converter utility that converts date object into smaller and relative time stamps like 2s, 2m, 4h and so on.
package com.dbws.fk.utils;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
/**
* Created by ayush on 14/9/15.
*/
public class RelativeTimeStamp {
/**
* converts date object into relative time stamp like 1s, 1m, 1h, 1d..6d, date
*
* @param date
* @return relative timestamp
*/
public static String getRelativeTimeStamp(Date date) {
String relative_time_stamp = "";
long orginal_time = date.getTime();
long current_time_stamp = Calendar.getInstance().getTimeInMillis();
long diff = current_time_stamp - orginal_time;
if (diff < (60 * 1000)) { // if less than 60s
relative_time_stamp = String.valueOf(diff / 1000) + "s"; // 1s
} else if (diff < (60 * 60 * 1000)) { // if less than 60 min
relative_time_stamp = String.valueOf(diff / (60 * 1000)) + "m"; // 2m
} else if (diff < (24 * 60 * 60 * 1000)) { // if less than 24 hours
relative_time_stamp = String.valueOf(diff / (60 * 60 * 1000)) + "h";
} else if (diff < (7 * 24 * 60 * 60 * 1000)) { // if less than 7 days
relative_time_stamp = String.valueOf(diff / (24 * 60 * 60 * 1000)) + "d";
} else { // if more than 7 days .. return human readable date
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("d MMM ''yy");
relative_time_stamp = simpleDateFormat.format(date);
}
return relative_time_stamp;
}
/**
* Converts default date time stamp into Date object
*
* @param datetime
* @return date
*/
public static Date getDateObject(String datetime) {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = null;
try {
date = simpleDateFormat.parse(datetime);
} catch (ParseException e) {
e.printStackTrace();
}
return date;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment