Otrzymuję ciąg daty 2021-06-13T15:00:00.000Z z odpoczynkowego połączenia api. Muszę przeanalizować ten ciąg daty, aby mecz zaczął się za 5 godzin lub dzisiaj

0
Amit Yadav 14 czerwiec 2021, 15:11

4 odpowiedzi

Najlepsza odpowiedź

Możesz spróbować czegoś takiego poniżej.

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

Dla API poniżej 26 Proszę również dodać następujące elementy w swoim 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")
}
2
DinkarKumar 15 czerwiec 2021, 15:30
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 "--"
            }
        }
    }
0
sashabeliy 14 czerwiec 2021, 12:16

Poniższy fragment kodu może pomóc:

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)
1
Amit Dash 15 czerwiec 2021, 17:43

Możesz po prostu obliczyć różnicę godzin między czasem obecnym a podanym. Jest na to więcej niż jeden sposób. Oto kilka

        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
1
che10 14 czerwiec 2021, 12:18