簡體   English   中英

比較 Android 中日期的最佳方法

[英]Best way to compare dates in Android

我正在嘗試將字符串格式的日期與當前日期進行比較。 這就是我的做法(尚未測試,但應該可以),但我使用的是已棄用的方法。 對替代方案有什么好的建議嗎? 謝謝。

PS 我真的很討厭在 Java 中做日期的事情。做同樣的事情有很多方法,你真的不確定哪一個是正確的,因此我的問題在這里。

String valid_until = "1/1/1990";

Calendar cal = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("dd/mm/yyyy");
Date strDate = sdf.parse(valid_until);

int year = strDate.getYear(); // this is deprecated
int month = strDate.getMonth() // this is deprecated
int day = strDate.getDay(); // this is deprecated       

Calendar validDate = Calendar.getInstance();
validDate.set(year, month, day);

Calendar currentDate = Calendar.getInstance();

if (currentDate.after(validDate)) {
    catalog_outdated = 1;
}

您的代碼可以簡化為

SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
Date strDate = sdf.parse(valid_until);
if (new Date().after(strDate)) {
    catalog_outdated = 1;
}

要么

SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
Date strDate = sdf.parse(valid_until);
if (System.currentTimeMillis() > strDate.getTime()) {
    catalog_outdated = 1;
}

您可以使用compareTo()

如果當前對象小於其他對象,CompareTo 方法必須返回負數,如果當前對象大於其他對象,則返回正數,如果兩個對象彼此相等,則返回零。

// Get Current Date Time
Calendar c = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy HH:mm aa");
String getCurrentDateTime = sdf.format(c.getTime());
String getMyTime="05/19/2016 09:45 PM ";
Log.d("getCurrentDateTime",getCurrentDateTime); 
// getCurrentDateTime: 05/23/2016 18:49 PM

if (getCurrentDateTime.compareTo(getMyTime) < 0)
{

}
else
{
 Log.d("Return","getMyTime older than getCurrentDateTime "); 
}

您可以直接從Date創建Calendar

Calendar validDate = new GregorianCalendar();
validDate.setTime(strDate);
if (Calendar.getInstance().after(validDate)) {
    catalog_outdated = 1;
}

請注意,在代碼工作之前正確的格式是 ("dd/MM/yyyy")。 “mm”表示分鍾!

String valid_until = "01/07/2013";
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
Date strDate = null;
try {
    strDate = sdf.parse(valid_until);
} catch (ParseException e) {
    e.printStackTrace();
}
if (new Date().after(strDate)) {
    catalog_outdated = 1;
}
String date = "03/26/2012 11:00:00";
String dateafter = "03/26/2012 11:59:00";
SimpleDateFormat dateFormat = new SimpleDateFormat(
        "MM/dd/yyyy hh:mm:ss");
Date convertedDate = new Date();
Date convertedDate2 = new Date();
try {
    convertedDate = dateFormat.parse(date);
    convertedDate2 = dateFormat.parse(dateafter);
    if (convertedDate2.after(convertedDate)) {
        txtView.setText("true");
    } else {
        txtView.setText("false");
    }
} catch (ParseException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}

它返回真。 您還可以在date.beforedate.equal的幫助下檢查 before 和 equal 。

Calendar toDayCalendar = Calendar.getInstance();
Date date1 = toDayCalendar.getTime();


Calendar tomorrowCalendar = Calendar.getInstance();
tomorrowCalendar.add(Calendar.DAY_OF_MONTH,1);
Date date2 = tomorrowCalendar.getTime();

// date1 is a present date and date2 is tomorrow date

if ( date1.compareTo(date2) < 0 ) {

  //  0 comes when two date are same,
  //  1 comes when date1 is higher then date2
  // -1 comes when date1 is lower then date2

 }

將日期轉換為日歷並在那里進行計算。 :)

Calendar cal = Calendar.getInstance();
cal.setTime(date);

int year = cal.get(Calendar.YEAR);
int month = cal.geT(Calendar.MONTH);
int day = cal.get(Calendar.DAY_OF_MONTH); //same as cal.get(Calendar.DATE)

要么:

SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
Date strDate = sdf.parse(valid_until);

if (strDate.after(new Date()) {
    catalog_outdated = 1;
}
try {
  SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");

  String str1 = "9/10/2015";
  Date date1 = formatter.parse(str1);

  String str2 = "10/10/2015";
  Date date2 = formatter.parse(str2);

  if (date1.compareTo(date2) < 0) {
    System.out.println("date2 is Greater than my date1");
  }

} catch (ParseException e1) {
  e1.printStackTrace();
}

在 Kotlin 中,使用內置函數 after() 或 before() 比較兩個時間對象非常簡單:

expirationTime.after(Date())
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd",Locale.getDefault());
Calendar calendar1 = Calendar.getInstance();
Calendar calendar2 = Calendar.getInstance();

Date date1 = dateFormat.parse("2013-01-01");
Date date2 = dateFormat.parse("2013-01-02");

calendar1.setTime(date1);
calendar2.setTime(date2);

System.out.println("Compare Result : " + calendar2.compareTo(calendar1));
System.out.println("Compare Result : " + calendar1.compareTo(calendar2));

將此 Calendar 表示的時間與給定 Calendar 表示的時間進行比較。

如果兩個 Calendar 的時間相等,則返回 0,如果此 Calendar 的時間在另一個 Calendar 之前,則返回 -1,如果此 Calendar 的時間在另一個 Calendar 之后,則返回 1。

現代答案的時間。

java.time 和 ThreeTenABP

    DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("d/M/u");
    String validUntil = "1/1/1990";
    LocalDate validDate = LocalDate.parse(validUntil, dateFormatter);
    LocalDate currentDate = LocalDate.now(ZoneId.of("Pacific/Efate"));
    if (currentDate.isAfter(validDate)) {
        System.out.println("Catalog is outdated");
    }

當我剛剛運行這段代碼時,輸​​出是:

目錄已過時

由於它在所有時區中的日期永遠不會相同,因此請為LocalDate.now指定明確的時區。 如果您希望目錄在所有時區同時到期,您可以提供ZoneOffset.UTC ,只要您通知您的用戶您正在使用 UTC。

我正在使用 java.time,現代 Java 日期和時間 API。 您使用的日期時間類CalendarSimpleDateFormatDate都設計得很差,幸運的是已經過時了。 此外,盡管名稱Date不代表日期,但代表一個時間點。 這樣做的一個后果是:即使今天是 2019 年 2 月 15 日,新創建的Date對象已經(因此不等於)解析15/02/2019Date對象之后。 這讓一些人感到困惑。 與此相反,現代LocalDate是沒有時間(也沒有時區)的日期,因此代表今天日期的兩個LocalDate將始終相等。

問題:我可以在 Android 上使用 java.time 嗎?

是的,java.time 在較舊和較新的 Android 設備上都能很好地工作。 它只需要至少Java 6

  • 在 Java 8 及更高版本和更新的 Android 設備(從 API 級別 26)中,現代 API 是內置的。
  • 在 Java 6 和 7 中獲得 ThreeTen Backport,現代類的 backport(ThreeTen for JSR 310;請參閱底部的鏈接)。
  • 在(較舊的)Android 上使用 ThreeTen Backport 的 Android 版本。 它被稱為 ThreeTenABP。 並確保使用子包從org.threeten.bp導入日期和時間類。

鏈接

你可以試試這個

Calendar today = Calendar.getInstance (); 
today.add(Calendar.DAY_OF_YEAR, 0); 
today.set(Calendar.HOUR_OF_DAY, hrs); 
today.set(Calendar.MINUTE, mins ); 
today.set(Calendar.SECOND, 0); 

您可以使用today.getTime()來檢索值並進行比較。

更新: Joda-Time庫現在處於維護模式,並建議遷移到繼承它的java.time框架。 請參閱Ole VV回答


喬達時間

java.util.Date 和 .Calendar 類是出了名的麻煩。 避開它們。 在 Java 8 中使用Joda-Time或新的 java.time 包。

本地日期

如果您只需要日期而沒有時間,請使用 LocalDate 類。

時區

獲取當前日期取決於時區。 一個新的日期在蒙特利爾之前在巴黎滾動。 指定所需的時區而不是依賴於 JVM 的默認值。

Joda-Time 2.3 中的示例。

DateTimeFormat formatter = DateTimeFormat.forPattern( "d/M/yyyy" );
LocalDate localDate = formatter.parseLocalDate( "1/1/1990" );
boolean outdated = LocalDate.now( DateTimeZone.UTC ).isAfter( localDate );

有時我們需要做一個帶有日期的列表,比如

今天一小時

昨天和昨天

23/06/2017 的其他日子

為此,我們需要將當前時間與我們的數據進行比較。

Public class DateUtil {

    Public static int getDateDayOfMonth (Date date) {
        Calendar calendar = Calendar.getInstance ();
        Calendar.setTime (date);
        Return calendar.get (Calendar.DAY_OF_MONTH);
    }

    Public static int getCurrentDayOfMonth () {
        Calendar calendar = Calendar.getInstance ();
        Return calendar.get (Calendar.DAY_OF_MONTH);
    }

    Public static String convertMillisSecondsToHourString (long millisSecond) {
        Date date = new Date (millisSecond);
        Format formatter = new SimpleDateFormat ("HH: mm");
        Return formatter.format (date);
    }

    Public static String convertMillisSecondsToDateString (long millisSecond) {
        Date date = new Date (millisSecond);
        Format formatter = new SimpleDateFormat ("dd / MM / yyyy");
        Return formatter.format (date);
    }

    Public static long convertToMillisSecond (Date date) {
        Return date.getTime ();
    }

    Public static String compare (String stringData, String yesterday) {

        String result = "";

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat ("yyyy-MM-dd HH: mm: ss");
        Date date = null;

        Try {
            Date = simpleDateFormat.parse (stringData);
        } Catch (ParseException e) {
            E.printStackTrace ();
        }

        Long millisSecond = convertToMillisSecond (date);
        Long currencyMillisSecond = System.currentTimeMillis ();

        If (currencyMillisSecond> millisSecond) {
            Long diff = currencyMillisSecond - millisSecond;
            Long day = 86400000L;

            If (diff <day && getCurrentDayOfMonth () == getDateDayOfMonth (date)) {
                Result = convertMillisSecondsToHourString (millisSecond);

            } Else if (diff <(day * 2) && getCurrentDayOfMonth () -1 == getDateDayOfMonth (date)) {
                Result = yesterday;
            } Else {
                Result = convertMillisSecondsToDateString (millisSecond);
            }
        }

        Return result;
    }
}

您也可以在GitHub和這篇文章中查看此示例。

您可以使用validDate.setTime(strDate)http://docs.oracle.com/javase/1.5.0/docs/api/java/util/Calendar.html查看 javadoc

SimpleDateFormat sdf=new SimpleDateFormat("d/MM/yyyy");
Date date=null;
Date date1=null;
try {
       date=sdf.parse(startDate);
       date1=sdf.parse(endDate);
    }  catch (ParseException e) {
              e.printStackTrace();
    }
if (date1.after(date) && date1.equals(date)) {
//..do your work..//
}

Kotlin 支持運算符重載

在 Kotlin 中,您可以使用比較運算符輕松比較日期。 因為 Kotlin 已經支持運算符重載。 所以要比較日期對象:

firstDate: Date = // your first date
secondDate: Date = // your second date

if(firstDate < secondDate){
// fist date is before second date
}

如果您使用的是日歷對象,則可以輕松地進行如下比較:

if(cal1.time < cal2.time){
// cal1 date is before cal2 date
}

暫無
暫無

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

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