比较字符串是否为日期格式ANDROID

时间:2016-03-18 07:39:55

标签: android

我收到的数据是从包含QR的{​​{1}}代码进行扫描的。但现在我想进行验证,代码将在仅扫描日期和时间时进入另一个活动。我在这里发布代码

DateTime

但是当我用日期和时间扫描qr代码时,这似乎是错误的,它会弹出吐司。数据应该像这样插入数据库

enter image description here

2 个答案:

答案 0 :(得分:0)

您必须将ScanResult-String解析为Date-Object。这是通过使用SimpleDateFormatter的parse()方法完成的。等于在这里不起作用!

尝试解析您的ScanResult:

SimpleDateFormat dateFormat =  new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");    
try {
    final Date dateResult = dateFormat.parse(scanResult);
    SimpleDateFormat outFormat =  new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
    final String formattedForDatabase = outFormat.format(dateResult);
    // TODO Do your stuff.
    new createClockIn().execute();
} catch (ParseException e) {
    Toast.makeText(BarcodeScanner.this, "Sorry this is not a valid date and time",  Toast.LENGTH_SHORT).show();
    Intent intent = new Intent(getApplicationContext(), BarcodeScanner.class);
    intent.putExtra("username", staffIDStr1);
    startActivity(intent);
}

答案 1 :(得分:0)

处理这样的例外:

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
try {
        sdf.parse(scanResult);
} catch (ParseException e) {
    // Invalid Date
    e.printStackTrace();
}