簡體   English   中英

檢查日期是否是今天Java的前一周

[英]Check if date is one week before from today Java

我正在嘗試檢查某個特定日期是否比今天的日期早一周。 我將日期格式化為以下格式:

SimpleDateFormat formatter = new SimpleDateFormat("MM/dd/yyyy hh:mm a");

然后,通過以下代碼從for循環中獲取日期列表:

Date formattedToday = formatter.parse(todayStr);
Date formattedExpired = formatter.parse(expiredDate);

列表中日期的示例為:

09/12/2017 08:09 PM
10/24/2015 02:09 AM
07/18/2018 03:10 AM

我嘗試遵循此線程,但不允許添加任何外部庫。

另一個需要Java 8解決方案也不適用於我,因為我當前的最小API是25,ChronoUnit需要API 26

有任何想法嗎? 謝謝!

您可以僅使用DateCalendar類(因此,是否與大約4位數的任何JVM兼容?),您可以嘗試以下解決方案:

  1. 以今天的Date作為DateDate now = new Date()
  2. 從中獲得一個星期前的CalendarCalendar expected = Calendar.getInstance(); expected.setTime(now); lastWeek.add(Calendar.WEEK_OF_YEAR, -1); Calendar expected = Calendar.getInstance(); expected.setTime(now); lastWeek.add(Calendar.WEEK_OF_YEAR, -1);
  3. 將到期日期作為Calendar獲取: Calendar actual = Calendar.getInstance().setTime(expiredDate);
  4. 比較兩個日歷的年份和年份(您可以比較其他字段,但是這兩個字段應該足夠): return (expected.get(Calendar.YEAR) == actual.get(Calendar.YEAR)) && (expected.get(Calendar.WEEK_OF_YEAR) == actual.get(Calendar.WEEK_OF_YEAR));

使用此功能,您應該能夠提出一個更短的代碼段,該代碼段從現在開始減去一周,然后比較兩者的長值。 雖然顯然不會比較日歷日期,但會比較納秒:)

這是一個完整的解決方案:

import java.util.Calendar;
import java.util.Date;

/**
 * @author Jeremi Grenier-Berthiaume
 */
public class InternalDate {

    private int year = 0;
    private int month = 0;
    private int day = 0;


    private InternalDate(int year, int month, int day){
        this.year = year;
        this.month = month;
        this.day = day;
    }

    private static InternalDate generateFromCalendar(Calendar calendar) {

        int lYear = calendar.get(Calendar.YEAR);
        int lMonth = calendar.get(Calendar.MONTH) + 1; // January = 1st month
        int lDay = calendar.get(Calendar.DAY_OF_MONTH);

        return new InternalDate(lYear, lMonth, lDay);
    }

    /**
     * Constructor for a textual format.
     *
     * @param text  Format "DD/MM/YYYY" followed by more chars which will be ignored if they are present.
     * @return      Associated InternalDate
     */
    private static InternalDate generateDateFromText(String text) {

        int year, month, day;
        char selectedChar = '/';
        text = text.substring(0,10); // to remove hours

        // Extract the data required to construct the InternalDate
        String[] splitDateText = text.split(""+selectedChar);
        day = Integer.parseInt(splitDateText[0]);
        month = Integer.parseInt(splitDateText[1]);
        year = Integer.parseInt(splitDateText[2]);

        return new InternalDate(year, month, day);
    }

    private static InternalDate getLastWeek() {

        // Get current date
        Calendar tempCal = Calendar.getInstance();
        tempCal.setTime(new Date());

        // 7 days ago
        tempCal.add(Calendar.DAY_OF_MONTH, -7);

        return generateFromCalendar(tempCal);
    }

    public static boolean isLastWeek(String compared) {

        int tmpDate = Integer.parseInt(InternalDate.getLastWeek().getComparableStringDate());
        int tmpCompDate = Integer.parseInt(InternalDate.generateDateFromText(compared).getComparableStringDate());

        return tmpDate == tmpCompDate;
    }
}

將要驗證的日期形成為DD/MM/YYYY格式的字符串,並將其輸入到InternalDate.isLastWeek(stringDate); 會給您答案(返回布爾值:如果是一周前的日期則為true否則為false )。

一個好又簡單的單行代碼,您可以在應用程序中的任何位置調用它。 如果它確實正確回答了您的問題,請隨意將其標記為答案。 :)

tl; dr

ZonedDateTime
.now()                           // Captures current moment as seen by the wall-clock time of the JVM’s current default time zone. Better to pass the optional `ZoneId` argument to specify explicitly the desired/expected time zone.
.minusWeeks( 1 )
.isAfter(
    LocalDateTime
    .parse( 
        "09/12/2017 08:09 PM" ,
        DateTimeFormatter.ofPattern( "MM/dd/uuuu hh:mm a" , Locale.US )
    )
    .atZone(
        ZoneId.systemDefault()   // Better to pass explicitly the time zone known to have been intended for this input. See discussion below.
    )
)

使用java.time

現代解決方案使用java.time類。 糟糕的舊版DateCalendar等更容易使用。

檢查日期是否是今天Java的前一周

您是否打算只處理日期而忽略時間? 我不會,因為您的輸入是一天中的某個時間。

獲取UTC當前時刻。

Instant instant = Instant.now() ;  // Current moment in UTC.

調整到作為日期時間輸入字符串的上下文所隱含的時區。 應用ZoneId以獲取ZonedDateTime對象。

continent/region的格式指定正確的時區名稱 ,例如America/MontrealAfrica/CasablancaPacific/Auckland 切勿使用ESTIST等3-4個字母的縮寫,因為它們不是真實的時區,不是標准化的,甚至不是唯一的(!)。

ZoneId z = ZoneId.of( "Africa/Tunis" ) ;      // Replace with the zone you know to have been intended for the input strings.
ZonedDateTime zdtNow = instant.atZone( z ) ;  // Adjust from UTC to a time zone.

減去一周,這是您在問題中提出的要求。

ZonedDateTime zdtWeekAgo = zdtNow.minusWeeks( 1 ) ; // Accounts for anomalies such as Daylight Saving Time (DST).

將輸入字符串解析為LocalDateTime對象,因為它們缺少任何時區或UTC偏移量指示符。

提示:盡可能更改這些輸入以包括其時區。 並更改其格式以使用標准ISO 8601格式而不是自定義格式。

DateTimeFormatter f = DateTimeFormatter.ofPattern( "MM/dd/uuuu hh:mm a" , Locale.US ) ;
LocalDateTime ldt = LocalDateTime.parse( "09/12/2017 08:09 PM" , f ) ;

分配已知用於這些輸入字符串的時區。

ZonedDateTime zdt = ldt.atZone( z ) ;

相比。

boolean moreThanWeekOld = zdt.isBefore( zdtWeekAgo ) ;

關於java.time

java.time框架內置於Java 8及更高版本中。 這些類取代了麻煩的舊的舊式日期時間類,例如java.util.DateCalendarSimpleDateFormat

現在處於維護模式Joda-Time項目建議遷移到java.time類。

要了解更多信息,請參見Oracle教程 並在Stack Overflow中搜索許多示例和說明。 規格為JSR 310

您可以直接與數據庫交換java.time對象。 使用與JDBC 4.2或更高版本兼容的JDBC驅動程序 不需要字符串,不需要java.sql.*類。

在哪里獲取java.time類?

獨立於Java 8

如何以簡單的方式做到這一點,即從兩個日期中獲取時間並找出difference 轉換此differencedays在兩個日期之間的差異獲取days 下面是工作代碼:

Date formattedToday = new Date();
Date formattedExpired = new Date("06/12/2018 08:09 PM");

int diffInDays = (int)( (formattedToday.getTime() - formattedExpired.getTime())
        / (1000 * 60 * 60 * 24) );

if (diffInDays > 7) 
Log.i("Expiration Status : ", "Expired");

它將為您提供兩個日期之間的差異(以days ,如果到期日期為將來,則可以為negative如果到期日期為過去,則可以為positive

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM