Requirements Description:
Given a date-time requirement to display only the time of day (for example, today 13:30), the date displayed yesterday was unchanged yesterday (for example, yesterday 13:30), and the other normal display date and time (for example, 2020-12-30 12:00:00). Similar to the phone recording time on the display.
Code Implementation
Add joda-time maven dependencies in Pom.xml:
<dependency>
<groupId>joda-time</groupId>
<artifactid>joda-time</artifactid >
<version>2.9.9</version>
</dependency>
The Java code is as follows:
Import Org.joda.time.DateTime;
Import Org.junit.Test;
Import Java.util.Date;
/** * ${description} * * @author Ricky Fung/public class Datetimetest {@Test public void Testformat () { SYSTEM.OUT.PRINTLN (Format (new Date ()); Today SYSTEM.OUT.PRINTLN (Format (new DateTime (New Date ()). Minusdays (1). ToDate ())); Yesterday System.out.println (Format (new DateTime (New Date ()). Minusdays (2). ToDate ())); 2 days ago SYSTEM.OUT.PRINTLN (Format (new DateTime (New Date ()). Plusdays (1). ToDate ()));
1 days later} private String format (date date) {datetime now = new DateTime ();
DateTime today_start = new DateTime (Now.getyear (), Now.getmonthofyear (), Now.getdayofmonth (), 0, 0, 0);
DateTime today_end = today_start.plusdays (1);
DateTime Yesterday_start = today_start.minusdays (1); if (Date.after (Today_start.todate ()) && Date.before (Today_end.todate ())) {return String.Format ("Today%s" , new DateTime (date). toString("hh:mm")); else if (Date.after (Yesterday_start.todate ()) && Date.before (Today_start.todate ())) {return STRING.F
Ormat ("Yesterday%s", new DateTime (date). toString ("hh:mm"));
return new DateTime (date). toString ("Yyyy-mm-dd hh:mm"); }
}
Run Result:
Today 13:31
Yesterday 13:31
2017-07-12 13:31
2017-07-15 13:31