简体   繁体   English

我如何计算预定义日期时间和最近日期时间之间的秒数差异

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

Well i am trying to define a date and see the difference with recent date in seconds. 好吧,我正在尝试定义一个日期,并以秒为单位查看与最近日期的区别。 Below is the code i did inside onCreate method of activity: 下面是我在活动的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));

But its not showing any result. 但是它没有显示任何结果。 :-( :-(

Change this 改变这个
Date d_recent = formata.parse("currentDateandTime"); to Date d_recent = formata.parse(currentDateandTime); Date d_recent = formata.parse(currentDateandTime);

please find the answer 请找到答案

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

See this similar question using Joda-Time. 使用Joda-Time看到类似的问题 Or use the new java.time package in Java 8. The old java.util.Date and .Calendar class's are notoriously troublesome and should be avoided. 或在Java 8中使用新的java.time包。众所周知,旧的java.util.Date和.Calendar类很麻烦,应避免。

Joda-Time 乔达时间

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