显示当前日期

时间:2015-09-15 02:46:49

标签: java android sqlite date

以下是我查询sqlite数据库的java代码的一些部分。如何在保存数据时添加自动当前日期?我使用的_DATE和_TIME是使用文本字段,但我想在保存日记时使用显示当前日期

private static final String DIARY_TABLE = "diarytable";
        private static final String _ID = "id";
        private static final String _NAME = "workout";
        private static final String _DATE = "date";
        private static final String _TIME = "time";
        private static final String _NOTES = "notes";

        public data(Context context) {
            super(context, DB_NAME, null, DB_VERSION);
            this.context=context;
        }



        @Override
        public void onCreate(SQLiteDatabase db) {
            try{
               // db.execSQL(CREATE_TABLE);
                db.execSQL("CREATE TABLE " + TABLE_NAME + " ( " + UID + " integer primary key autoincrement," +
                        "" + NAME + " VARCHAR(50), " +
                        "" + _STATUS + " VARCHAR(255)," +
                        "" + WEIGHT + " VARCHAR(255));");
                message.mess(context,"Database Created");

 //               db.execSQL(CREATE_TABLE1);
                db.execSQL("CREATE TABLE "+ DIARY_TABLE+ " ( "+_ID+" integer primary key autoincrement," +
                        ""+_NAME+" VARCHAR(50), " +
                        ""+_DATE+" VARCHAR(10)," +
                        ""+_TIME+" VARCHAR(5)," +
                        ""+_NOTES+" VARCHAR(255));");
                message.mess(context,"Second Database Created");

            }
            catch(SQLException e){
                message.mess(context, "Failed" +e);
            }
        }

3 个答案:

答案 0 :(得分:1)

尝试

 String getCurrentDateTime = DateFormat.getDateTimeInstance().format(new Date());
 String getCurrentDate = new SimpleDateFormatDateFormat.getDateTimeInstance("yyyy-MM-dd").format(new Date());

答案 1 :(得分:0)

  1. 了解要存储到db中的日期格式。
    Eg. dd/MM/yyyy, MM-dd-yyyy

  2. 从系统

  3. 获取日期
  4. 将系统日期格式化为您声明的格式。

  5. 这是代码

       DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd");
       Calendar cal = Calendar.getInstance();
       System.out.println(dateFormat.format(cal.getTime()));
    

    结果将是这样的2015/09/15。然后,您可以将日期存储到数据库中。

答案 2 :(得分:0)

这是显示当前日期时间的简单方法。我在项目中使用的代码下面。

    TextView date1=(TextView)findViewById(R.id.tvdatetime);
    time1=(TextView)findViewById(R.id.tvtime);
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    dt1 = sdf.format(new Date());
    // textView is the TextView view that should display it
    date1.setText(dt1);
    datevalue=date1.getText().toString();
    //Shows Current time 
    Time today = new Time(Time.getCurrentTimezone());
    today.setToNow();
    time1.setText(today.format("%k:%M:%S"));
    timevalue=time1.getText().toString();