【问题标题】:Pass a string value to Long将字符串值传递给 Long
【发布时间】:2016-09-17 14:46:54
【问题描述】:

我把这个日期和时间连接成一个字符串,我做对了吗?因为我想将 strDateTime 传递给 Long 类型(因为它的构造函数是 Long) 这是代码

public void DT(){
        seldate = (TextView) findViewById(R.id.receivedate);
        newDate = seldate.getText().toString();
        timeChose = time1.getText().toString();
        final   TimePicker tp = (TimePicker) findViewById(R.id.timePicker1);

        strDateTime = newDate + " "+ timeChose ;
        DatabaseSource sched = new DatabaseSource(
                subject.getText().toString(),
                description.getText().toString(),
                strDateTime.toLong()
        );
        long result = dbHelper.addSched(sched);
        if(result>0){
            Toast.makeText(getApplicationContext(),"Added", Toast.LENGTH_SHORT).show();
        }
        else {
            Toast.makeText(getApplicationContext(),"Add Failed", Toast.LENGTH_SHORT).show();
        }
}

P.S 选择的日期,我将其保存到首选项键,然后获取它并传递到下一个活动中的文本视图(我将在其中创建事件)然后单击 timepickerdialog 时我有一个编辑文本的时间弹出然后设置编辑文本字段本身的时间。

【问题讨论】:

  • strDateTime的格式是什么?
  • 字符串 strDateTime
  • 我的意思是它是像17-09-2016这样的格式吗?显示示例日期。
  • 哦,是的,(yyyy-MM-dd)
  • 你需要将时间戳传递给函数吗?

标签: android datetime


【解决方案1】:

将yyyy-MM-dd 格式的日期解析为Date 对象。 使用getTime 方法获取时间戳,单位为毫秒。

试试这个,

String strDateTime = "2016-09-17 11:21 PM";

SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm aa");
long milliseconds = 0;
try {
    Date date = format.parse(strDateTime);
    milliseconds = date.getTime();
} catch (Exception e) {
    e.printStackTrace();
}

// pass milliseconds to the method
DatabaseSource sched = new DatabaseSource(
        subject.getText().toString(),
        description.getText().toString(),
        milliseconds
);

【讨论】:

  • 我忘了strDateTime是和时间连接的,所以日期和时间都连接在strDateTime(字符串)中,所以可能要保存在数据库中的格式是这样的(2016- 09-17 11:21 PM)作为数据库中的 DATETIME 数据类型
  • 那么在strDateTime.toLong()那一行,是这样吗??因为另一个类的构造函数是这样的(String,String,Long)?
  • 嗯,我可以保存数据,但我无法检索数据。没有任何迹象或错误,只是数据不会加载到屏幕上
  • 当前问题上没有错误但我不确定数据是否正确插入,因为我无法检索数据。我正在使用 WHERE 子句来检索数据,并且我使用数据库中的 DueDate (DATETIME),所以这意味着如果我使用 WHERE 子句并且我没有得到任何东西,这意味着 DueDate 没有价值。现在,我尝试删除 WHERE 子句,我能够检索数据。但是,我确实需要使用 where 子句进行比较,所以我以这种方式使用它 WHERE DueDate LIKE "' + text + '");
  • 所以没有插入数据。所以使用字符串而不是长字符串。将构造函数更改为 (String,String,String)
【解决方案2】:

使用此代码Long.parseLong("0", 0);

这里"0"是你的字符串值,0是默认值(如果字符串为空或不是数字格式)

【讨论】:

    猜你喜欢
    • 2011-05-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-13
    • 2020-04-08
    • 2016-06-01
    • 2011-08-16
    • 1970-01-01
    相关资源
    最近更新 更多