【问题标题】:compare string whether its in a date format ANDROID [duplicate]比较字符串是否为日期格式ANDROID [重复]
【发布时间】:2016-03-18 07:39:54
【问题描述】:

您好,我从 QR 代码中扫描到包含 DateTime 的数据。但现在我想在哪里进行验证,当代码仅扫描日期和时间时,代码将继续进行另一个活动。我把代码贴在这里

 Log.i("<<<<<<Asset Code>>>>> ",
                        "<<<<Bar Code>>> " + sym.getData());
                scanResult = sym.getData().trim();


                SimpleDateFormat dateFormat =  new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");

                if(scanResult.equals(dateFormat))
                {
                    new createClockIn().execute();
                }

                else {
                    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);

                }

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

【问题讨论】:

  • scanResult 是什么类型的?字符串

标签: android


【解决方案1】:

您必须将 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);
}

【讨论】:

  • 你能给我一个扫描结果的示例字符串吗?
  • 我把我的数据库的图片。扫描二维码时,数据将插入数据库。这些数据没有我现在想做的验证
  • *在问题中(图片)
  • 对不起,我不敢相信。这应该有效。你的 logcat 的输出是什么。 Log.i(">>>> ", ">> " + sym.getData());
  • 如何在logcat中找到?
【解决方案2】:

这样处理异常:

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

【讨论】:

  • @ekinidris 你在 scanResult 中得到什么字符串?
  • 你是什么意思?它应该是日期和时间。我把图片放在问题中
  • @ekinidris 在这种情况下是有效格式
  • 是的,我也这么认为,但它仍然给出错误,它不是有效的日期时间格式
  • @ekinidris 不认为请调试应用程序并告诉我们您在 scanResult 中得到了什么。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-07-04
  • 2013-06-24
  • 1970-01-01
  • 1970-01-01
  • 2011-10-07
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多