Java to determine whether a date is today, yesterday __java

Source: Internet
Author: User

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





Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.