科特林的日期和时间

时间:2020-07-19 18:14:34

标签: datetime kotlin time

我是科特林的新手。而且我遇到了问题。

我有此代码:

val sdf = SimpleDateFormat("dd.MM.yyyy")
val currentDate = sdf.format(Date())
println(currentDate)

val stringDate = "12.03.2015"
val dateFormatter = DateTimeFormatter.ofPattern("dd.MM.yyyy", Locale.ENGLISH)
val millisecondsSinceEpoch = LocalDate.parse(stringDate, dateFormatter)
    .atStartOfDay(ZoneOffset.UTC)
    .toInstant()
    .toEpochMilli()
println(millisecondsSinceEpoch)

val time = currentDate - millisecondsSinceEpoch
val Datee = sdf.format(time)
println(Datee)

但是在线:

val time = currentDate - millisecondsSinceEpoch
val Datee = sdf.format(time)
println(Datee)

我得到了错误:

java.lang.IllegalArgumentException: Cannot format given Object as a Date

请帮助我如何解决此问题。我需要从字符串中的日期中减去当前日期。

更新:

如何正确地从另一个日期减去一个日期并获得天数差异?

3 个答案:

答案 0 :(得分:2)

我建议您从过时的java.util日期/时间API切换到modern date/time API。下面给出的是您所需的Java代码,希望您能够将其转换为Kotlin。但是,如果您遇到任何问题,我可以为您将其转换为Kotlin代码。

import java.time.Duration;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.Period;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;

public class Main {
    public static void main(String[] args) {
        // Define format
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd.MM.yyyy", Locale.ENGLISH);

        // Given date-time
        ZonedDateTime givenDateTime = LocalDateTime.of(LocalDate.parse("12.03.2015", formatter), LocalTime.of(0, 0))
                .atZone(ZoneId.of("Etc/UTC"));

        // Now
        ZonedDateTime zdtNow = ZonedDateTime.now(ZoneId.of("Etc/UTC"));

        // Period between the two dates
        Period period = Period.between(givenDateTime.toLocalDate(), zdtNow.toLocalDate());

        // Given date-time with current year, month and day
        ZonedDateTime adjusted = givenDateTime.with(LocalDate.now(ZoneId.of("Etc/UTC")));

        // Duration between the two times
        Duration duration = Duration.between(adjusted, zdtNow);

        // Display each part of the period and duration
        System.out.printf("%d years %d month %d days %d hours %d minutes %d seconds %d nanoseconds", period.getYears(),
                period.getMonths(), period.getDays(), duration.toHoursPart(), duration.toMinutesPart(),
                duration.toSecondsPart(), duration.toNanosPart());
    }
}

输出:

5 years 4 month 7 days 19 hours 30 minutes 37 seconds 507058000 nanoseconds

使用OffsetDateTime

import java.time.Duration;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.OffsetDateTime;
import java.time.Period;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.Locale;

public class Main {
    public static void main(String[] args) {
        // Define format
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd.MM.yyyy", Locale.ENGLISH);

        // Given date-time
        OffsetDateTime givenDateTime = LocalDateTime.of(LocalDate.parse("12.03.2015", formatter), LocalTime.of(0, 0))
                .atOffset(ZoneOffset.UTC);

        // Now
        OffsetDateTime odtNow = OffsetDateTime.now(ZoneOffset.UTC);

        // Period between the two dates
        Period period = Period.between(givenDateTime.toLocalDate(), odtNow.toLocalDate());

        // Given date-time with current year, month and day
        OffsetDateTime adjusted = givenDateTime.with(LocalDate.now(ZoneOffset.UTC));

        // Duration between the two times
        Duration duration = Duration.between(adjusted, odtNow);

        // Display each part of the period and duration
        System.out.printf("%d years %d month %d days %d hours %d minutes %d seconds %d nanoseconds", period.getYears(),
                period.getMonths(), period.getDays(), duration.toHoursPart(), duration.toMinutesPart(),
                duration.toSecondsPart(), duration.toNanosPart());
    }
}

答案 1 :(得分:1)

以下是初始程序的更正版本。但是,正如其他人指出的那样,建议使用新的Java Time API。

有一篇很好的文章强调了旧的Java日期和日历API的问题 https://programminghints.com/2017/05/still-using-java-util-date-dont/

import java.util.Date
import java.util.Locale
import java.time.Instant
import java.time.LocalDateTime
import java.time.LocalDate
import java.time.ZoneOffset
import java.text.SimpleDateFormat
import java.time.format.DateTimeFormatter

fun main(args: Array<String>) {
val sdf = SimpleDateFormat("dd.MM.yyyy")
val currentDate = Date()
val currentFormattedDate = sdf.format(currentDate)
println(currentFormattedDate)
val now = currentDate.getTime();
    
val stringDate = "12.03.2015"
val dateFormatter = DateTimeFormatter.ofPattern("dd.MM.yyyy", Locale.ENGLISH)
val millisecondsSinceEpoch = LocalDate.parse(stringDate, dateFormatter)
    .atStartOfDay(ZoneOffset.UTC)
    .toInstant()
    .toEpochMilli()
println(millisecondsSinceEpoch)

val time = now - millisecondsSinceEpoch
val Datee = sdf.format(time)
println(Datee)
}

答案 2 :(得分:0)

谢谢大家。但是我决定这样做。似乎一切正常)

fun daysString(dataend: String):String{
    val dateFormat = SimpleDateFormat("dd.MM.yyyy")
    val endDate = dateFormat.parse(dataend)
    val currentDate = Date()
    val time = endDate.time - currentDate.time
    val days = time / 1000 / 3600 / 24
    val strtoday = days.toString()
    return strtoday
}

现在在我使用的代码中:

val data_end = "10.10.2020"
daysString(data_end)

我就开始了