2012-10-28 19 views
5

どのように私のsqliteデータベースにdatetimeデータを挿入することができますcontentvalues生のクエリを使用していない?sqliteデータベースにdatetimeを挿入する

datetime( 'now')は時間ではなく、それ自身を挿入します(現在の時間に追加時間を追加できますか?ミリ秒に

答えて

6

変換日付/時間..私は、ボタン「1時間」を押すと、それはちょっと混乱し、sqliteのdatabase..thanksにCURRENTTIME + 1時間を挿入する、などの

、あなたはlongを取得します。次に、longの値をデータベースに挿入するだけです。

日付/時刻の値をミリ秒単位で追加できます。 SQLiteので

--EDITED--

Date myDate = new Date(); 
    long timeMilliseconds = myDate.getTime(); 
    //add 1 hour 
    timeMilliseconds = timeMilliseconds + 3600 * 1000; //3600 seconds * 1000 milliseconds 
    //To convert back to Date 
    Date myDateNew = new Date(timeMilliseconds); 

ジャワlongintとして記憶されます。

+0

私は構文を表示できますか、私はそれをどのように変換できますか? – mcr619619

+1

私の答えに追加 – Luis

+0

ありがとう!!!これは私が必要なものです..私は長い間、すべてを挿入すると、私は取得し、私の欲しいやり方でそれを変換することができますが、私はフォーマット(YYYY-DD -MM)私はそれを取得することはできません、私はそれを取得する場合、それは年を取得し、getStringを介して、その唯一の文字列、私は実際のミリに変換することはできません、回避策はありますか?私は長い方法を使用することができますが、それは私のデータベースでより便利になる場合は、読み取り可能なものです..おかげで..本当に私を助けた – mcr619619

1

Javaラッパー "ContentValues"を使用してdatetime関数を使用することはできません。あなたはこの方法で実装できます

1)あなたはuseSQLiteDatabase.execSQL(生のSQLクエリ)

dbObj.execSQL("INSERT INTO "+DATABASE_TABLE+" VALUES (null, datetime()) "); 

2)あなたはSimpleDateFormatの

// setting the format to sql date time 
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 
Date date = new Date(); 
ContentValues initialValues = new ContentValues(); 
initialValues.put("date_time", dateFormat.format(date)); 
long recordId = mDb.insert(DB_TABLE_NAME, null, initialValues); 

3を使用することができます)あなたが日付値を格納することができますデータベースを(ロングタイプの)ミリ秒として表示することができます。表示するには、

import java.text.DateFormat; 
import java.text.SimpleDateFormat; 
import java.util.Calendar; 

System.out.println(getDate(82233213123L, "dd/MM/yyyy hh:mm:ss.SSS")); 

// Return date in specified format. 
// milliSeconds Date in milliseconds 
// dateFormat Date format 
// return date as string in specified format 

public static String formatDate(long milliSeconds, String dateFormat) 
{ 

    DateFormat formatter = new SimpleDateFormat(dateFormat); 

// Create a calendar object that will convert the date and time value in milliseconds to date. 
    Calendar calendar = Calendar.getInstance(); 
calendar.setTimeInMillis(milliSeconds); 
return formatter.format(calendar.getTime()); 
    } 
} 

1秒= 1000 M 1時間を追加したい場合は、この式を使用してください。

currentTImeMilli + (60 * 60 * 1000) 
+0

私は、しかし、system.currentmillsを使用して、それをフォーマットする..ありがとう。それは動作します、私は日付を取得する場合、今私は新しい質問を持って、 "2012-10-28 09:58:15"私はそれをsystem.currentmillisが使用する形式に変換する方法は?私のアプリケーションでは、現在の時刻と特定の時刻(この場合は+ 1時間)を比較する必要があるため、 – mcr619619

関連する問題