将日期字符串 2021-06-13T15:00:00.000Z 格式化为剩余的小时数

问题描述

我从 rest api 调用接收日期字符串 2021-06-13T15:00:00.000Z。我必须解析这个日期字符串,匹配将在 5 小时后开始今天

解决方法

您可以尝试如下操作。

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'",Locale.getDefault());
    LocalDateTime eventDate = LocalDateTime.parse("2021-06-15T21:00:00.000Z",formatter);
    LocalDateTime now = LocalDateTime.now();
    Duration dur = Duration.between(now,eventDate);
    if (dur.isNegative()) {
        Log.d("DINKAR","Time Already Passed");
    } else if (dur.isZero()) {
        Log.d("DINKAR","Its happening now");
    } else {
        if (dur.getSeconds() > 0 && dur.getSeconds() < 60) {
            Log.d("DINKAR",String.format("Match will start in %d seconds",dur.getSeconds()));
        } else if (dur.toMinutes() > 0 && dur.toMinutes() < 60) {
            Log.d("DINKAR",String.format("Match will start in %d minutes",dur.toMinutes()));
        } else if (dur.toHours() > 0 && dur.toHours() < 24) {
            Log.d("DINKAR",String.format("Match will start in %d hours",dur.toHours()));
        } else if (dur.toDays() > 0) {
            Log.d("DINKAR",String.format("Match will start in %d days",dur.toDays()));
        }
    }

对于低于 26 的 API,请同时在 build.gradle 中添加以下内容

android {
defaultConfig {
    // Required when setting minSdkVersion to 20 or lower
    multiDexEnabled = true
}

compileOptions {
    // Flag to enable support for the new language APIs
    coreLibraryDesugaringEnabled = true
    // Sets Java compatibility to Java 8
    sourceCompatibility = JavaVersion.VERSION_1_8
    targetCompatibility = JavaVersion.VERSION_1_8
}
}

dependencies {
    coreLibraryDesugaring("com.android.tools:desugar_jdk_libs:1.1.5")
}
,

以下代码片段可能会有所帮助:

val timeInString = "2021-06-16T05:00:00.000Z"
val givenTime = ZonedDateTime.parse(timeInString).toLocalDateTime()
val currentTime = ZonedDateTime.now().toLocalDateTime()
val difference = Duration.between(currentTime,givenTime)

val matchTimeMessage = when {
    difference.isNegative -> "The match is already over"
    difference.toHours() < 24 -> "The match will start in ${difference.toHours()} hours"
    else -> "The match will start in ${difference.toDays()} days"
}

println(matchTimeMessage)
,

您可以简单地计算当前时间和给定时间之间的小时差。有不止一种方法可以做到这一点。这里有一些

        val givenTime = Instant.parse("2021-06-13T15:00:00.000Z")
        val currentTime = Instant.now()

        val difference1 = ChronoUnit.HOURS.between(currentTime,givenTime)  // Use Chronounit
        val difference2 = Duration.between(currentTime,givenTime).toHours()    // Use Duration
,
private  fun getAppropriateTimeDiffResolution(
        start: Date?,end: Date?
    ): String {
        return if (start != null && end != null) {
            val diffInMs: Long = end.time - start.time
            val diffInMins: Long = TimeUnit.MILLISECONDS.toMinutes(diffInMs)
            val diffInHrs: Long = TimeUnit.MILLISECONDS.toHours(diffInMs)
            val diffInDays: Long = TimeUnit.MILLISECONDS.toDays(diffInMs)
            val diffInMonth: Long = TimeUnit.MILLISECONDS.toDays(diffInMs) / 30
            val diffInYear = diffInMonth / 12
            val stringBuilder = StringBuilder()
            if (diffInMins < 60) {
                if (diffInMins > 1) stringBuilder.append(diffInMins)
                    .append(" Mins Ago")
                    .toString() else if (diffInMins == 0L) "Now" else stringBuilder.append(
                    diffInMins
                ).append(" Mins Ago").toString()
            } else if (diffInHrs < 24) {
                stringBuilder.append(diffInHrs)
                    .append(" Hours Ago")
                    .toString()
            } else if (diffInDays < 30) {
                stringBuilder.append(diffInDays)
                    .append(" Days Ago").toString()
            } else if (diffInMonth < 12) {
                stringBuilder.append(diffInMonth)
                    .append(" Months Ago")
                    .toString()
            } else {
                stringBuilder.append(diffInYear)
                    .append(" Years Ago").toString()

            }
        } else {
            "--"
        }
    }

  private  fun getFormattedTime(@NonNull time: String): String {
        Log.e("BindingAdapter",time)

        val input = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssX",Locale.getDefault())
        var d: Date?
        try {
            d = input.parse(time)
            return getAppropriateTimeDiffResolution(d,Date())
        } catch (e: ParseException) {
            try {
                val fallback =
                    SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'",Locale.getDefault())
                d = fallback.parse(time)
                return getAppropriateTimeDiffResolution(d,Date())
            } catch (e2: ParseException) {
                return "--"
            }
        }
    }