Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import android.util.Log;
- import java.text.DateFormat;
- import java.text.SimpleDateFormat;
- import java.util.Calendar;
- import java.util.Date;
- import java.util.Locale;
- import java.util.TimeZone;
- /**
- * Created by rachmadi on 4/13/17.
- */
- public class Utility {
- String TAG = "Utility";
- public String getPostTime(long timeStamp){
- String postTime = "";
- Date dLastDate = null;
- TimeZone timezone = TimeZone.getDefault();
- DateFormat objFormatter = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
- objFormatter.setTimeZone(timezone);
- Calendar objCalendar = Calendar.getInstance(timezone);
- objCalendar.setTimeInMillis(timeStamp);
- String result = objFormatter.format(objCalendar.getTime());
- objCalendar.clear();
- String datePost = result;
- SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss", Locale.getDefault());
- String dateCurrent = dateFormat.format(new Date());
- //HH converts hour in 24 hours format (0-23), day calculation
- SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss", Locale.getDefault());
- Date d1 = null;
- Date d2 = null;
- try {
- d1 = format.parse(datePost);
- d2 = format.parse(dateCurrent);
- //in milliseconds
- long diff = d2.getTime() - d1.getTime();
- long diffSeconds = diff / 1000 % 60;
- long diffMinutes = diff / (60 * 1000) % 60;
- long diffHours = diff / (60 * 60 * 1000) % 24;
- long diffDays = diff / (24 * 60 * 60 * 1000);
- String firstDate = datePost.substring(0, 10);
- String secondDate = dateCurrent.substring(0, 10);
- if (!firstDate.equals(secondDate)) {
- SimpleDateFormat lastDateDf = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
- dLastDate = lastDateDf.parse(result);
- SimpleDateFormat dLastDateDf = new SimpleDateFormat("dd MMM yy, HH:mm");
- postTime = dLastDateDf.format(dLastDate);
- }
- else if (diffDays < 1) {
- if (diffHours > 0){
- postTime = String.valueOf(diffHours) + " jam lalu";
- } else if (diffMinutes > 0){
- postTime = String.valueOf(diffMinutes) + " menit lalu";
- } else if (diffSeconds > 0){
- postTime = String.valueOf(diffSeconds) + " detik lalu";
- } else if (diffDays == 0) {
- postTime = "1 detik lalu";
- }
- }
- } catch (Exception e) {
- e.printStackTrace();
- Log.d(TAG, "error: " + e.toString());
- }
- return postTime;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement