2013-04-23 31 views
0

我對Java/Android開發有點新,我需要比較兩次。其中一個時間值存儲在一個字符串中,另一個存儲在系統時間的當前時間(長) - 我怎樣才能找出兩次以毫秒爲單位的差異並將其存儲爲一個數字?Android - 將時間字符串與當前時間進行比較減去差值並轉換爲毫秒

編輯:

嘗試#1(響應懶惰忍者)

public class Rules extends Activity { 

private String password; 

private PendingIntent mPendingIntent; 
String TIMELIMIT = "10"; 

TextView textSsid, textSpeed, textRssi, Time; 
private static final int NOTIFY_ME_ID = 1337; 
private int count = 0; 
private NotificationManager notifyMgr = null; 
public Handler mHandler = new Handler(); 
public long mStartRX = 0; 
public long mStartTX = 0; 
public long txBytes; 

@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.rules); 

    String NDEF_PREF = "prefs"; 
    SharedPreferences prefs = getSharedPreferences(NDEF_PREF, 
      Context.MODE_PRIVATE); 
    String name = prefs.getString("name", ""); 
    String code = prefs.getString("corename", ""); 
    String time = prefs.getString("time", ""); 
    String ssid = prefs.getString("restricted", ""); 
    Time = (TextView) findViewById(R.id.Time); 
    Time.setText(time); 

    String dtStart = "09:27:37"; 
    SimpleDateFormat format = new SimpleDateFormat("HH:mm:ss"); 
    try { 
     Date date = format.parse(time); 
    } catch (ParseException e) { 
     e.printStackTrace(); 
    } 

    Long convertedLong = date.getTimeInMillis(); 

    long currentTimeLong = System.currentTimeMillis(); 
    long difference = currentTimeLong - convertedLong; 
    String strDiff = String.valueOf(difference); 

問題:

日期不能得到解決Rules.java的Java問題

回答

1

確定轉換您的字符串到datetime:

String dtStart = "09:27:37"; 
SimpleDateFormat format = new SimpleDateFormat("HH:mm:ss"); 
try { 
    Date date = format.parse(dtStart); 
} catch (ParseException e) { 
    // TODO Auto-generated catch block 
    e.printStackTrace(); 
} 

然後將其轉換爲毫秒

long convertedLong = date.getTimeInMillis(); 

然後

long currentTimeLong = System.currentTimeMillis(); // will get you current time in milli 
long difference = currentTimeLong - convertedLong; 
String strDiff = String.valueOf(difference); 

從那裏數學currentTimeLong - convertedLong。

+0

Long.parseLong(time)會這樣嗎? (有些東西告訴我必須有更多的東西來獲取當前系統時間和我的時間字符串值之間的差異,然後將其轉換爲毫秒。 – 2013-04-23 02:52:18

+0

我的字符串不是以毫秒爲單位 - 它是標準格式(例如11: 00),我無法找到一種方法來做到這一點谷歌 - 或所以我發佈它作爲一個新的問題!:) – 2013-04-23 02:55:05

+0

@JamesLaur System.currentTimeMillis()是在毫秒的權利?這就是爲什麼我說我假設字符串以毫秒爲單位。 – 2013-04-23 02:55:47