问题
I need to print date like today,Yesterday,2 days ago like that for that i have done
I am getting date like : String date1 = "Thu Nov 13 19:01:25 GMT+05:30 2014";
calling like str=get_userTime(date1);
private String get_userTime(String usertime) {
Date d = null;
// String datee = "Thu Nov 13 19:01:25 GMT+05:30 2014";
String datee = usertime;
SimpleDateFormat inputFormat = new SimpleDateFormat(
"EE MMM dd HH:mm:ss zz yyy");
try {
d = inputFormat.parse(datee);
} catch (java.text.ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
SimpleDateFormat outputFormat1 = new SimpleDateFormat("MM/dd/yyyy");
System.out.println(outputFormat1.format(d));
op = outputFormat1.format(d);
op=formatToYesterdayOrToday(op);
return op;
}
and this is another function to get yesterday/today i have use this Link
public static String formatToYesterdayOrToday(String date) {
date=op;
DateTime dateTime = DateTimeFormat.forPattern("EEE hh:mma MMM d, yyyy")
.parseDateTime(date);
DateTime today = new DateTime();
DateTime yesterday = today.minusDays(1);
DateTimeFormatter timeFormatter = DateTimeFormat.forPattern("hh:mma");
if (dateTime.toLocalDate().equals(today.toLocalDate())) {
return "Today " + timeFormatter.print(dateTime);
} else if (dateTime.toLocalDate().equals(yesterday.toLocalDate())) {
return "Yesterday " + timeFormatter.print(dateTime);
} else {
return date;
}
}
But getting Error:
11-21 13:12:10.626: E/AndroidRuntime(20654): java.lang.IllegalArgumentException: Invalid format: "11/21/2014"
11-21 13:12:10.626: E/AndroidRuntime(20654): at org.joda.time.format.DateTimeFormatter.parseDateTime(DateTimeFormatter.java:871)
On
DateTime dateTime = DateTimeFormat.forPattern("EEE hh:mma MMM d, yyyy")
.parseDateTime(date); //In (formatToYesterdayOrToday())
I have used Joda-time.jar
回答1:
You can try this code: (delta is time in milliseconds)
public static String getDisplayableTime(long delta)
{
long difference=0;
Long mDate = java.lang.System.currentTimeMillis();
if(mDate > delta)
{
difference= mDate - delta;
final long seconds = difference/1000;
final long minutes = seconds/60;
final long hours = minutes/60;
final long days = hours/24;
final long months = days/31;
final long years = days/365;
if (seconds < 0)
{
return "not yet";
}
else if (seconds < 60)
{
return seconds == 1 ? "one second ago" : seconds + " seconds ago";
}
else if (seconds < 120)
{
return "a minute ago";
}
else if (seconds < 2700) // 45 * 60
{
return minutes + " minutes ago";
}
else if (seconds < 5400) // 90 * 60
{
return "an hour ago";
}
else if (seconds < 86400) // 24 * 60 * 60
{
return hours + " hours ago";
}
else if (seconds < 172800) // 48 * 60 * 60
{
return "yesterday";
}
else if (seconds < 2592000) // 30 * 24 * 60 * 60
{
return days + " days ago";
}
else if (seconds < 31104000) // 12 * 30 * 24 * 60 * 60
{
return months <= 1 ? "one month ago" : days + " months ago";
}
else
{
return years <= 1 ? "one year ago" : years + " years ago";
}
}
return null;
}
回答2:
for Android you can use the most simple way with Joda-Time-Android library:
Date yourTime = new Date();
DateTime dateTime = new DateTime(yourTime); //or simple DateTime.now()
final String result = DateUtils.getRelativeTimeSpanString(getContext(), dateTime);
回答3:
DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
DateTime datetime = formatter.parseDateTime(time); // time = string time data
LocalDate localDate = new LocalDateTime(datetime).toLocalDate();
LocalDate localDateNow = new LocalDateTime().toLocalDate();
int diff = Days.daysBetween(localDate, localDateNow).getDays();
Then just use the diff to evaluate which day.
回答4:
In you DateTimeFormatter, it expects a Date in a certain format, i.e. "EEE hh:mma MMM d, yyyy"
:
DateTime dateTime = DateTimeFormat.forPattern("EEE hh:mma MMM d, yyyy")
.parseDateTime(date);
But what you pass, is of format "MM/dd/yyyy"
:
SimpleDateFormat outputFormat1 = new SimpleDateFormat("MM/dd/yyyy");
op = outputFormat1.format(d);
op = formatToYesterdayOrToday(op);
So, what you could do is to change your DateTimeFormatter to expect you initial format "MM/dd/yyyy"
:
DateTime dateTime = DateTimeFormat.forPattern("MM/dd/yyyy")
.parseDateTime(date);
This should solve the error that you get. I don't know if the whole thing in the end gives you what you want ("today", "yesterday", "2 days ago", ...).
回答5:
This should give the output you want.
Use SimpleDateFormat to parse your date and then use
date.getTime()
in the following;
long now = System.currentTimeMillis();
DateUtils.getRelativeTimeSpanString(your time in long, now, DateUtils.MINUTE_IN_MILLIS);
回答6:
This can now be easily achieved using the method in Android DateUtils as below.
DateUtils.getRelativeTimeSpanString(feedItem.timeStamp)
You can get outputs like,
1 hours ago, Yesterday, 2 days ago
回答7:
I am using the following the function to get RemainingTime but the format is almost same as you want. try this code and do changes as per your requirement.
/**
* To convert expire time according to selected format(period)
* @param period
* @return
*/
public String getExpireDate(int period) {
int days = 0, weeks = 0, hours = 0, mins = 0, secs = 0;
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date systemDate = Calendar.getInstance().getTime();
String myDate = sdf.format(systemDate);
long millse = // your time in milliseconds
if (millse < 0) {
return activity.getResources().getString(R.string.already_expire);
}
long mills = Math.abs(millse);
if (mills > 60480000) {
weeks = (int) (mills / 604800000);
mills = mills % 604800000;
days = (int) (mills / 86400000);
mills = mills % 86400000;
hours = (int) (mills / 3600000);
mills = mills % 3600000;
mins = (int) (mills / 60000);
mills = mills % 60000;
secs = (int) (mills / 1000);
} else if (mills > 86400000) {
days = (int) (mills / 86400000);
mills = mills % 86400000;
hours = (int) (mills / 3600000);
mills = mills % 3600000;
mins = (int) (mills / 60000);
mills = mills % 60000;
secs = (int) (mills / 1000);
} else if (mills > 3600000) {
hours = (int) (mills / 3600000);
mills = mills % 3600000;
mins = (int) (mills / 60000);
mills = mills % 60000;
secs = (int) (mills / 1000);
}
String remainingTime = "";
switch (period) {
case SHORT_PERIOD:
if (weeks > 0) {
if (weeks == 1) {
remainingTime = weeks + " week";
} else {
remainingTime = weeks + " weeks";
}
} else if (days > 0) {
if (days == 1) {
remainingTime = days + " day";
} else {
remainingTime = days + " days";
}
} else if (hours > 0) {
if (hours == 1) {
remainingTime = hours + " hour";
} else {
remainingTime = hours + " hours";
}
} else if (mins > 0) {
if (mins == 1) {
remainingTime = mins + " minute";
} else {
remainingTime = mins + " minutes";
}
} else {
if (secs == 1) {
remainingTime = secs + " second";
} else {
remainingTime = secs + " seconds";
}
}
break;
case DETAILED_PERIOD:
if (weeks > 0) {
remainingTime = (weeks * 7) + days + " days," + hours
+ " hours," + mins + " minutes";// + secs + " secs";
} else if (days > 0) {
remainingTime = days + " days," + hours + " hours," + mins
+ " minutes";// + secs + " seconds";
} else if (hours > 0) {
remainingTime = hours + " hours," + mins + " minutes";// + secs
// +
// " seconds";
} else if (mins > 0) {
remainingTime = mins + " minutes";// + secs + " seconds";
}
break;
case EXACT_DATE_TIME:
SimpleDateFormat target = new SimpleDateFormat("dd-MMM-yyyy");
try {
remainingTime = target.format(sdf.parse(taskData
.getTask_expire_date()));
} catch (ParseException e) {
e.printStackTrace();
}
break;
default:
break;
}
return remainingTime;
}
回答8:
Imagine you have data like this:
{"data":[{"id":"79tiyfjgdfg","sales_name":"Sengkuni","sales_branch":"Kingdom of Hastina","message":"Leader of Kurowo sent you a gold","timestamp":"2020-03-23 10:16:01"}]}
and call function like this:
holder.timestamp.setText(Utils.beautifyDate(context, notifications.get(position).getTimestamp(), "EEEE, MMMM d, YYYY"));
for another format you can check from https://developer.android.com/reference/java/text/SimpleDateFormat
Use this function below
public static String beautifyDate(Context context, String timestamp, String formatDate) {
String beautifyFormat;
SimpleDateFormat fmt = new SimpleDateFormat("yyyy-M-dd H:mm:ss", Locale.getDefault());
Date date = new Date();
try {
date = fmt.parse(timestamp);
} catch (Exception e) {
e.printStackTrace();
}
String mYear = new SimpleDateFormat("yyyy", Locale.getDefault()).format(date);
String mMonth = new SimpleDateFormat("M", Locale.getDefault()).format(date);
String mDay = new SimpleDateFormat("dd", Locale.getDefault()).format(date);
String mHour = new SimpleDateFormat("H", Locale.getDefault()).format(date);
String mMinutes = new SimpleDateFormat("mm", Locale.getDefault()).format(date);
Calendar now = Calendar.getInstance();
int years = now.get(Calendar.YEAR);
int months = now.get(Calendar.MONTH) + 1;
int days = now.get(Calendar.DATE);
int hours = now.get(Calendar.HOUR_OF_DAY);
int minutes = now.get(Calendar.MINUTE);
if (mYear.equals(String.valueOf(years)) && mMonth.equals(String.valueOf(months)) && mDay.equals(String.valueOf(days))) {
Log.i("timestamp", "on same day");
hours -= Integer.parseInt(mHour);
beautifyFormat = hours > 1 ? hours + " " + context.getString(R.string.hours_ago): hours + " " + context.getString(R.string.hour_ago);
if (hours == 0) {
minutes -= Integer.parseInt(mMinutes);
beautifyFormat = minutes > 1 ? minutes + " " + context.getString(R.string.minutes_ago): context.getString(R.string.moments_ago);
}
} else {
days = now.get(Calendar.DATE) - Integer.parseInt(mDay);
if (days == 1) {
beautifyFormat = context.getString(R.string.tomorrow);
} else {
beautifyFormat = new SimpleDateFormat(formatDate, Locale.getDefault()).format(date);
}
}
return beautifyFormat;
}
simply adjust the time you want to be able to see results like today or tomorrow and others
Hope it is useful.
来源:https://stackoverflow.com/questions/27056530/android-in-date-write-today-yesterday-2-days-ago-like-that