Reputation: 575
I am learning format date and time in android, I want to try to convert the date and time as the timeline ... ? example:
String current_date = "2013-10-07 20:57:20";
String val_date1 = "2013-10-07 20:57:20";
String val_date2 = "2013-10-07 19:57:20";
String val_date3 = "2013-10-07 17:57:20";
String val_date4 = "2013-09-07 20:57:20";
above date and adjusted CURRENT_DATE converted and the results such as these:
String val_date1_after_formated = "just now";
String val_date2_after_formated = "1h";
String val_date3_after_formated = "3h";
String val_date4_after_formated = "1d";
how to convert date with the program? I hope anyone can help me. Sorry if my English is not good ...
Upvotes: 1
Views: 963
Reputation: 14183
Here a function that should do the job
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
int[] steps = {1,60,3600,3600*24};
String[] names = {"seconds","minutes","hours","days"};
//...
public String formatDelay(String date){
try {
Date d = sdf.parse(date);
Long stamp = d.getTime()/1000;
Long now = System.currentTimeMillis()/1000;
Long dif = now - stamp;
if(stamp > now) return "";
for(int i=0;i<steps.length;i++){
if(dif<steps[i]){
String output = Long.toString(dif/steps[i-1])+" "+names[i-1];
return output;
}
}
return Long.toString(dif/steps[3])+" "+names[3];
} catch (Exception e){
e.printStackTrace();
return "";
}
Upvotes: 3
Reputation: 8495
Not sure if this is what your looking for but to get the current time use this. Returns in milliseconds.
System.currentTimeMillis() / 1000L;
To format it to a time date-time use this code.
long loadDate = System.currentTimeMillis() / 1000L;
String dateString = new SimpleDateFormat("MM/dd/yyyy").format(new Date(loadDate));
Upvotes: 0
Reputation: 45942
formatDuration
might be good for this:
public String getDuration(long time) {
StringBuilder sb = new StringBuilder();
android.support.v4.util.TimeUtils.formatDuration(System.currentTimeMillis() - date, sb);
return sb.toString();
}
Now to get the long time
you need to parse the input dates (maybe using SimpleDateFormat
).
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.US);
long date = sdf.parse("2013-10-07 20:57:20").getTime();
String duration = getDuration(date);
Upvotes: 1