簡體   English   中英

我如何計算預定義日期時間和最近日期時間之間的秒數差異

[英]How can i calculate difference in seocnds between a predefined date time and recent date time

好吧,我正在嘗試定義一個日期,並以秒為單位查看與最近日期的區別。 下面是我在活動的onCreate方法中執行的代碼:

    txtNowTime = (TextView)findViewById(R.id.textViewNow);

    SimpleDateFormat formata = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");

    String currentDateandTime = formata.format(new Date());

    @SuppressWarnings("deprecation")
    Date oldd = new Date("07/18/2014 11:12:13");
    String olddt_frmt = formata.format(oldd);

    long diff =0;
    try {
          Date d_recent = formata.parse("currentDateandTime");

           diff = d_recent.getTime() - oldd.getTime();


        } catch (ParseException ex) {
             ex.printStackTrace();          }

     txtNowTime.setText(String.valueOf(diff));

但是它沒有顯示任何結果。 :-(

改變這個
Date d_recent = formata.parse("currentDateandTime"); Date d_recent = formata.parse(currentDateandTime);

請找到答案

SimpleDateFormat formata = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss", Locale.getDefault());
String currentDateandTime = formata.format(new Date());
long diff = 0;
try {
Date d_recent = formata.parse(currentDateandTime);
Date olddt_frmt = formata.parse("07/18/2014 11:12:13");
diff = d_recent.getTime() - olddt_frmt.getTime();
} catch (ParseException ex) {
    ex.printStackTrace();
}

使用Joda-Time看到類似的問題 或在Java 8中使用新的java.time包。眾所周知,舊的java.util.Date和.Calendar類很麻煩,應避免。

喬達時間

DateTime then = DateTime.now();
//…
DateTime now = DateTime.now();
Seconds seconds = Seconds.secondsBetween( now, then );
int secondsElapsed = seconds.getSeconds();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM