Home > Java > JavaBase > Java determines whether the date is today

Java determines whether the date is today

Release: 2019-11-20 11:16:43
Original
8846 people have browsed it

Java determines whether the date is today

java determines whether the date is the current day:

public static boolean isToday(String str, String formatStr) throws Exception{
    SimpleDateFormat format = new SimpleDateFormat(formatStr);
    Date date = null;
    try {
        date = format.parse(str);
    } catch (ParseException e) {
        logger.error("解析日期错误", e);
    }
    Calendar c1 = Calendar.getInstance();              
    c1.setTime(date);                                 
    int year1 = c1.get(Calendar.YEAR);
    int month1 = c1.get(Calendar.MONTH)+1;
    int day1 = c1.get(Calendar.DAY_OF_MONTH);     
    Calendar c2 = Calendar.getInstance(); 
    c2.setTime(new Date());
    int year2 = c2.get(Calendar.YEAR);
    int month2 = c2.get(Calendar.MONTH)+1;
    int day2 = c2.get(Calendar.DAY_OF_MONTH);   
    if(year1 == year2 && month1 == month2 && day1 == day2){
        return true;
    }
    return false;   
}
Copy after login

In the above code, formatStr is the date format we need to verify. For example, I need to verify whether "20161212" is the current day. , then formatStr is "yyyyMMdd".

For example, if we need to verify whether "2016-12-12" is the same day, it will be "yyyy-MM-dd". For example, if we need to verify the string of "2016/12/12", it will be " yyyy/MM/dd", and so on.

Use the constructor SimpleDateFormat(String str) of the SimpleDateFormat class in java to construct the format of the formatted date.

Format the specified date object into the specified format through the format(Date date) method String.

For more java knowledge, please pay attention to java basic tutorial.

The above is the detailed content of Java determines whether the date is today. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template