2015-09-27 59 views
0

我從php-server(String zeit)通過JSONObject獲取時間戳。我如何從當前獲得「時間以來」值的響應時間戳中減去當前時間?我希望我已經制定了我可以理解的問題。從PHP時間戳(字符串)減去時間

try { 
      // Checking for SUCCESS TAG 
      int success = json.getInt(TAG_SUCCESS); 

      if (success == 1) { 
       // products found 
       // Getting Array of Products 
       tische = json.getJSONArray(TAG_TISCHE); 

       // looping through All Products 
       for (int i = 0; i < tische.length(); i++) { 
        JSONObject c = tische.getJSONObject(i); 

        // Storing each json item in variable 
        String id = c.getString(TAG_ID); 
        String name = c.getString(TAG_NAME); 
        String wer = c.getString(TAG_KELLNER); 
        String zeit = c.getString(TAG_ZEIT); 

        String str_date="2015-09-23 17:53:00"; //string date & time of old time time stamp 
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss"); //format for string to date conversion 
        Date date = (Date)formatter.parse(str_date); //string to date convert 
        long oldtime = date.getTime(); //date to milliseconds base 1970-01-01 

        Calendar nowdate = Calendar.getInstance(); //pick present time 
        long nowtime = nowdate.getTimeInMillis(); //convert to milli seconds 

        long timediff = nowtime-oldtime;  //find difference 
        String zeitdiff = Long.toString(timediff); 
        System.out.println("difference is " + (timediff/(1000*3600*24))+ " days"); 

        // creating new HashMap 
        HashMap<String, String> map = new HashMap<String, String>(); 

        // adding each child node to HashMap key => value 
        map.put(TAG_ID, id); 
        map.put(TAG_NAME, name); 
        map.put(TAG_KELLNER, wer); 
        map.put(TAG_ZEIT, zeitdiff); 

        // adding HashList to ArrayList 
        productsList.add(map); 
       } 
      } else { 
+0

你想做到這一點在客戶端或服務器? Android或PHP? –

+0

我想在android中做到這一點!如果它已完成:我想看到我的應用程序中的「countup」 – user3713946

+0

什麼是zeit的字符串值? –

回答

2

以下是查找時間差異的代碼。

String str_date="2015-09-23 17:53:00"; //string date & time of old time time stamp 
DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss"); //format for string to date conversion 
Date date = (Date)formatter.parse(str_date); //string to date convert 
long oldtime = date.getTime(); //date to milliseconds base 1970-01-01 

Calendar nowdate = Calendar.getInstance(); //pick present time 
long nowtime = nowdate.getTimeInMillis(); //convert to milli seconds 

long timediff = nowtime-oldtime;  //find difference 
System.out.println("difference is " + (timediff/(1000*3600*24))+ " days"); 

在這裏,你申請你的邏輯就像timediff/1000爲秒,timediff/1000*60爲分鐘等

+0

感謝您的回答!是否可以自動刷新每秒的時間而不刷新活動? – user3713946

+0

在哪行代碼?把它放在裏面試試catch .. –

+0

我已經解決了這個問題!在else子句之後,我添加了cath(java.text.ParseException e) 是否有可能每秒刷新一次「timediff」而不刷新整個活動? – user3713946