【问题标题】:Android: Compare time in this format `yyyy-mm-dd hh:mm:ss` to the current momentAndroid:以这种格式“yyyy-mm-dd hh:mm:ss”的时间与当前时刻进行比较
【发布时间】:2013-10-26 14:19:02
【问题描述】:

我想获取设备上的当前时间,格式为:2013-10-17 15:45:01 ?

服务器将上述格式的对象的日期作为字符串发送给我。现在我想获取手机当前时间,然后检查是否有超过 5 分钟的差异?

所以 A:我怎样才能以这种格式获取设备的当前时间:2013-10-17 15:45:01

B 我怎样才能算出两者之间的区别。

【问题讨论】:

  • 你可能想看看SampleDateFormat
  • 您不想执行 A,因为比较字符串日期时间将是一场噩梦。您想将服务器字符串转换为日期时间,然后与当前手机时间进行比较。stackoverflow.com/questions/3941357/…
  • @YeLinAung 不,永远不要使用糟糕的遗留类SimpleDateFormatCalendarDate。它们在几年前被现代的 java.time 类所取代,并一致采用了JSR 310。示例代码见my Answer

标签: android date datetime time


【解决方案1】:

您可以使用SimpleDateFormat 指定您想要的模式:

new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(new java.util.Date())

但是,如果您只想知道时间差是否在某个阈值内,您可能应该只比较 long 值。如果您的阈值是 5 分钟,那么这是 5 * 60 * 1000 毫秒,因此您可以通过调用 parse 方法来使用相同的 SimpleDateFormat 并检查长值。

例子:

new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").parse("2013-10-13 14:54:03").getTime()

【讨论】:

  • 你应该指定一个语言环境,例如Locale.US,作为new SimpleDateFormat(...) 构造函数中的第二个参数。
【解决方案2】:

Date currentDate = new Date(); 将使用当前时间初始化一个新日期。另外,convert服务器提供时间和取差价。

String objectCreatedDateString = "2013-10-17 15:45:01";  
SimpleDateFormat  format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 
Date objectCreatedDate = null;
Date currentDate = new Date();
try 
{objectCreatedDate = format.parse(objectCreatedDateString);} 
catch (ParseException e) 
{Log.e(TAG, e.getMessage());}
int timeDifferential;
if (objectCreatedDate != null)
    timeDifferential = objectCreatedDate.getMinutes() - currentDate.getMinutes();

【讨论】:

  • 您实际上不必将 System.currentTimeMillis() 提供给 java.util.Date 构造函数 - 它会使用当前时间自动初始化。但是你必须指定新的操作符。
【解决方案3】:

tl;博士

Duration.between(  // Calculate time elapsed between two moments.
    LocalDateTime  // Represent a date with time-of-day but lacking the context of a time zone or offset-from-UTC.
        .parse( "2013-10-17 15:45:01".replace( " " , "T" ) )
        .atOffset( ZoneOffset.UTC )  // Returns an `OffsetDateTime` object.
        .toInstant() ,  // Returns an `Instant` object.
    Instant.now() // Capture the current moment as seen in UTC.
)
.toMinutes()
> 5

java.time

其他答案已经过时,使用了多年前被 JSR 310 中定义的现代 java.time 类所取代的糟糕类。

解析传入的字符串。

String input = "2013-10-17 15:45:01" ;

修改输入以符合 ISO 8601。我建议您对数据的发布者进行有关 ISO 8601 标准的教育。

String inoutModified = input.replace( " " , "T" ) ;

解析为LocalDateTime,因为此输入缺少预期偏移量或时区的指示符。

LocalDateTime ldt = LocalDateTime.parse( input ) ;

我假设输入旨在表示 UTC 中的时刻,偏移量为 0 小时分钟秒。如果是这样,请根据 ISO 8601 教育您的数据发布者在末尾附加 Z 以表明这一点。

OffsetDateTime odt = ldt.atOffset( ZoneOffset.UTC ) ;

提取一个更简单类的对象Instant。此类始终采用 UTC。

Instant then = odt.toInstant() ;

获取以 UTC 显示的当前时刻。

Instant now = Instant.now() ; 

计算差异。

Duration d = Duration.between( then , now ) ; 

获取持续时间作为总分钟数。

long minutes = d.toMinutes() ;

测试。

if ( minutes > 5 ) { … }

关于java.time

java.time 框架内置于 Java 8 及更高版本中。这些类取代了麻烦的旧 legacy 日期时间类,例如 java.util.DateCalendarSimpleDateFormat

要了解更多信息,请参阅Oracle Tutorial。并在 Stack Overflow 上搜索许多示例和解释。规格为JSR 310

Joda-Time 项目现在位于maintenance mode,建议迁移到java.time 类。

您可以直接与您的数据库交换 java.time 对象。使用符合JDBC 4.2 或更高版本的JDBC driver。不需要字符串,不需要java.sql.* 类。 Hibernate 5 & JPA 2.2 支持 java.time

从哪里获取 java.time 类?

【讨论】:

    【解决方案4】:

    使用 SimpleDateFromat 类

    DateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
    dateFormatter.format(date);
    

    也可以查看documentation

    【讨论】:

      【解决方案5】:

      如果您可以要求服务器向您发送符合 RFC3339 的日期/时间字符串,那么以下是您两个问题的简单答案:

      public String getClientTime() {
          Time clientTime = new  Time().setToNow();
          return clientTime.format("%Y-%m-%d %H:%M:%S");
      }
      
      public int diffClientAndServerTime(String svrTimeStr) {
          Time svrTime = new Time();
          svrTime.parse3339(svrTimeStr);
      
          Time clientTime = new  Time();
          clientTime.setToNow();
          return svrTime.compare( svrTime, clientTime);
      }
      

      【讨论】:

        猜你喜欢
        • 2017-07-09
        • 2015-10-08
        • 2014-09-22
        • 1970-01-01
        • 2016-12-02
        • 2014-12-26
        • 1970-01-01
        • 1970-01-01
        • 2020-03-07
        相关资源
        最近更新 更多