2016-03-18 28 views
0

嗨它得到了從QR碼掃描與包含DateTime數據。但是現在我想進行驗證,代碼將在僅掃描日期和時間時繼續執行另一個活動。我張貼在這裏的代碼比較字符串我是否日期格式ANDROID

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

       } 

但這似乎是錯誤的,當IM掃描日期和時間,它彈出來敬酒的QR碼。這些數據應被插入到數據庫中這樣

enter image description here

+0

是什麼類型scanResult?字符串 – Christopher

+0

是的,它是字符串 –

回答

0

你必須解析ScanResult字符串成日期 - 對象。這是通過使用SimpleDateFormatter的parse()方法完成的。 Equals在這裏不起作用!

嘗試解析您的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); 
} 
+0

它不工作:( –

+0

你能給我一個掃描結果的字符串的例子嗎? – Christopher

+0

我把我的數據庫的圖片當qr代碼掃描,數據將插入到數據庫。不,我想現在要做的 –

0

處理異常這樣的:

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

它不工作:( –

+0

@ekinidris什麼字符串你在scanResult獲得? – Amy

+0

你是什麼意思?它應該是日期和時間。我把圖片在 –