i can suggest you one thing. When u send the sms store the details into a database so that u can display the date and time on which the sms was sent in the history page.
Calendar now = Calendar.getInstance();
long secs = (dateToCompare - now.getTime().getTime()) / 1000;
if (secs > 0) {
int hours = (int) secs / 3600;
if (hours <= 24) {
return today + "," + "a formatted day or empty";
} else if (hours <= 48) {
return yesterday + "," + "a formatted day or empty";
}
} else {
int hours = (int) Math.abs(secs) / 3600;
if (hours <= 24) {
return tommorow + "," + "a formatted day or empty";
}
}
return "a formatted day or empty";
Calendar mDate = Calendar.getInstance(); // just for example
if (DateUtils.isToday(mDate.getTimeInMillis())) {
//format one way
} else {
//format in other way
}
DateUtils.isToday() should be considered deprecated because android.text.format.Time is now deprecated.
Until they update the source code for isToday, there is no solution here that detects today, yesterday, handles shifts to/from daylight saving time, and does not use deprecated code. Here it is in Kotlin, using a today field that must be kept up to date periodically (e.g. onResume etc):
@JvmStatic
fun dateString(ctx: Context, epochTime: Long): String {
val epochMS = 1000*epochTime
val cal = Calendar.getInstance()
cal.timeInMillis = epochMS
val yearDiff = cal.get(Calendar.YEAR) - today.get(Calendar.YEAR)
if (yearDiff == 0) {
if (cal.get(Calendar.DAY_OF_YEAR) >= today.get(Calendar.DAY_OF_YEAR))
return ctx.getString(R.string.today)
}
cal.add(Calendar.DATE, 1)
if (cal.get(Calendar.YEAR) == today.get(Calendar.YEAR)) {
if (cal.get(Calendar.DAY_OF_YEAR) == today.get(Calendar.DAY_OF_YEAR))
return ctx.getString(R.string.yesterday)
}
val flags = if (yearDiff == 0) DateUtils.FORMAT_ABBREV_MONTH else DateUtils.FORMAT_NUMERIC_DATE
return DateUtils.formatDateTime(ctx, epochMS, flags)
}
As mentioned, DateUtils.isToday(d.getTime()) will work for determining if Date d is today. But some responses here don't actually answer how to determine if a date was yesterday. You can also do that easily with DateUtils:
Without any library and simple code, work on every Kotlin project
//Simple date format of the day
val sdfDate = SimpleDateFormat("dd/MM/yyyy")
//Create this 2 extensions of Date
fun Date.isToday() = sdfDate.format(this) == sdfDate.format(Date())
fun Date.isYesterday() =
sdfDate.format(this) == sdfDate.format(Calendar.getInstance().apply {
add(Calendar.DAY_OF_MONTH, -1) }.time)
//And after everwhere in your code you can do
if(myDate.isToday()){
...
}
else if(myDate.isYesterday()) {
...
}