首頁 > Java > Java基礎 > 主體

java判斷日期是否是今天

發布: 2019-11-20 11:16:43
原創
8743 人瀏覽過

java判斷日期是否是今天

java判斷日期是不是當天:

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;   
}
登入後複製

上述程式碼中formatStr 是我們需要校驗的日期形式,例如我需要校驗「20161212」是否是當天,那麼formatStr為"yyyyMMdd"。

例如我們需要校驗“2016-12-12”是不是當天,就為“yyyy-MM-dd”,比如需要校驗“2016/12/12”的字符串,就為“ yyyy/MM/dd”,依次類推即可。

java中使用SimpleDateFormat類別的建構子SimpleDateFormat(String str)建構格式化日期的格式,

透過format(Date date)方法將指定的日期物件格式化為指定格式的字串.

更多java知識請關注java基礎教學

以上是java判斷日期是否是今天的詳細內容。更多資訊請關注PHP中文網其他相關文章!

相關標籤:
來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!