2016-07-06 78 views
3

我想要獲取今天和即將到期的日期之間的日期差異。這是我實施的代碼。但是這並沒有返回正確的輸出結果。在sqlite中獲取日期差異

public String[] getDaysList(){ 
    Cursor cursor = db.query("COUPON", null, null, null, null, null, null); 
    if(cursor.getCount()<1){ 
     cursor.close(); 
     return null; 
    } 
    String[] array = new String[cursor.getCount()]; 
    int i=0; 
    while(cursor.moveToNext()){ 

     String days = "(julianday('now') - julianday(EXPIRED_DATE))"; 
     array[i] = days; 
     i++; 
    } 
    return array; 
} 

這將返回(julianday('now') - julianday(EXPIRED_DATE))。請幫助我在這裏獲取日期差異作爲字符串到數組。

回答

0

你好,請嘗試以下一個

Cursor cursor = db.rawQuery("SELECT julianday('now') - julianday(DateCreated) FROM COUPON", null); 

if (cursor.moveToFirst()) { 
       do { 
        array[i]=cursor.getString(0) 
       } while (cursor.moveToNext()); 

      } 
+0

沒有天顯示爲「18.4855」,但實際天數爲「18」。如何修正小數位數。 – tenten

1

now修改不僅返回日期,但也是時間。

要更改時間戳的日期開始,使用date() function

SELECT julianday(date('now')) - julianday(EXPIRED_DATE) FROM ... 

(如果過期列還包含時間值,你必須使用date()它,太)

而實際執行這一點,你必須把它給數據庫:

public String[] getDaysList() { 
    String days = "julianday(date('now')) - julianday("+EXPIRED_DATE+")"; 
    Cursor cursor = db.query("COUPON", 
          new String[]{ days }, // query returns one column 
          null, null, null, null, null); 
    try { 
     String[] array = new String[cursor.getCount()]; 
     int i = 0; 
     while (cursor.moveToNext()) { 
      array[i++] = cursor.getString(0);  // read this column 
     } 
     return array.length > 0 ? array : null; 
    } finally { 
     cursor.close(); 
    } 
} 

(和天數是不是一個字符串;考慮全光照改爲int[]