Android:将格式为`yyyy-mm-dd hh:mm:ss`的时间与当前时间进行比较

9

我想以这种格式获取设备的当前时间:2013-10-17 15:45:01?

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

A:如何以此格式2013-10-17 15:45:01获取设备的当前时间。

B:如何计算两者之间的差异。


你可能想要查看SampleDateFormat - Ye Lin Aung
你不想做A,因为比较字符串日期时间会很麻烦。你需要将服务器字符串转换为日期时间,然后与当前手机时间进行比较。https://dev59.com/OW865IYBdhLWcg3wLrlE#3941395 - Simon
1
@YeLinAung 不要使用可怕的遗留类SimpleDateFormatCalendarDate。多年前,它们被现代的java.time类所取代,并通过JSR 310得到了一致的采用。请参见我的答案中的示例代码。 - Basil Bourque
6个回答

8
您可以使用 SimpleDateFormat 来指定您想要的日期时间格式:
new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(new java.util.Date())

然而,如果你只想知道时间差是否在某个阈值内,那么你应该比较长整型数值。如果你的阈值是5分钟,则为5 * 60 * 1000毫秒,因此你可以通过调用相同的SimpleDateFormat对象的parse方法来检查长整型数值。

示例:

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

new SimpleDateFormat(...) 构造函数的第二个参数中,您应该指定一个区域设置,例如 Locale.US - caw

2

Date currentDate = new Date();会使用当前时间初始化一个新的日期。此外,服务器提供的时间进行转换并计算差值。

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

2
你不需要向java.util.Date构造函数提供System.currentTimeMillis() - 它会自动初始化为当前时间。但是你必须指定new操作符。 - mvmn

2

简而言之

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

其他答案已经过时,使用的类已被现代的java.time类所替代,这些类在JSR 310中定义。

解析您的输入字符串。

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

修改输入以符合ISO 8601标准。我建议你向你的数据发布者介绍ISO 8601标准。

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

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

LocalDateTime ldt = LocalDateTime.parse( input ) ;

我猜测输入意图是表示一个以协调世界时(UTC)为基准的时间点,偏移量为零小时零分零秒。如果是这样,请告诉数据发布者,在结尾添加Z标记以便清晰表明,符合ISO 8601标准。

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 及以后的版本中。这些类替代了陈旧而麻烦的旧日期时间类,如 java.util.DateCalendar & SimpleDateFormat

要了解更多信息,请参见 Oracle 教程。同时,在 Stack Overflow 上搜索许多示例和解释。规范为 JSR 310

现在处于维护模式的 Joda-Time 项目建议迁移到 java.time 类。

您可以直接与数据库交换 java.time 对象。使用符合 JDBC 4.2 或更高版本的 JDBC 驱动程序。无需字符串,也无需 java.sql.* 类。Hibernate 5 和 JPA 2.2 支持 java.time

在哪里获取 java.time 类?

Table of which java.time library to use with which version of Java or Android


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

还要检查这个文档


0
如果您可以要求服务器发送符合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);
}

0

我也尝试了这个方法,最终它对我起作用了:

fun getTimeAgo(dateString: String): String {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        val then = LocalDateTime.parse(dateString
            .replace(" ","T"))
            .atOffset(ZoneOffset.UTC)
            .toInstant()
        val now = LocalDateTime.now().atOffset(ZoneOffset.UTC).toInstant()
        val diff = Duration.between(then, now).seconds
        return when {
            diff < 60 -> "$diff seconds ago"
            diff < 3600 -> "${diff / 60} minutes ago"
            diff < 86400 -> "${diff / 3600} hours ago"
            else -> "${diff / 86400} days ago"
        }
    } else {
        return dateString
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接