【问题标题】:How to save a Date from DatePicker into SQLite with Android Studio如何使用 Android Studio 将 DatePicker 中的日期保存到 SQLite
【发布时间】:2016-11-08 22:13:28
【问题描述】:

我的 Android 应用项目有一个 SQLite 数据库,我想从日期选择器中保存一个日期。 为了尽可能高效,我不能将该日期作为字符串插入。 所以我试图将我的日期保存为整数或长整数,但我在网上查遍了所有内容,但没有足够清楚的信息来帮助我......

这是我的代码:

   public DatePickerDialog.OnDateSetListener myDateListener = new DatePickerDialog.OnDateSetListener() {
    @Override
    public void onDateSet(DatePicker view, int year, int month, int day) {

        // Do something with the chosen date
        TextView dateView = (TextView) findViewById(R.id.newdatepicked);

        // Create a Date variable/object with user chosen date
        Calendar cal = Calendar.getInstance();
        cal.setTimeInMillis(0);
        cal.set(year, month, day, 0, 0, 0);

        Date date = cal.getTime();  // CAN I USE THIS LINE?

        // Format the date using style MEDIUM and FR locale
        DateFormat df_date = DateFormat.getDateInstance(DateFormat.LONG, Locale.FRANCE);
        String dateDF= df_date.format(dateDF);
        // Display the formatted date
        dateView.setText(dateDF);

    }
};

以及插入所有数据的代码:

  public void SaveAlert(View v) {

    String Article = tvArticle.getText().toString();
    long DateEntree = calendar.getTimeInMillis(); // This line is working very well
    long DateSortie =                   ;///////// I CANNOT FIND OUT HOW TO HANDLE THIS ...

我的问题是 DateSortie。

请让我为我的英语道歉,非常感谢您的帮助

【问题讨论】:

  • 您在 textview 中显示选定日期。所以只需将 dateDF 值保存为数据库中的字符串

标签: android database sqlite date datepicker


【解决方案1】:

您仍然可以将其存储为字符串,然后使用您想要的格式检索它们,例如

  Calendar calendar = Calendar.getInstance();

   /* to display time*/
   SimpleDateFormat formatter = new SimpleDateFormat("hh:mm");

    /* to display date in the given format */
   DateFormat dateFormatter = new SimpleDateFormat("dd/MM/yyyy");  

   /*get the date using */
   Date dDate = dateFormatter.parse(yourObject.getTaskDate());

   /*set the date */
   calendar.setTime(dDate);

【讨论】:

  • 感谢您的回答,我知道如何用字符串插入它,但我读过它最好保存为整数以按日期排序为例。
  • 这可能会帮助您使用日历 [stackoverflow.com/a/13694823/6213163] 将您选择的日期转换为时间戳
  • 嗨,@Anirudh,感谢您的帮助,它工作正常;)
  • 很高兴有帮助:)
猜你喜欢
  • 2017-10-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-12-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多