Implement the following pattern in Java and Kotlin (almost the same) with Date and Time API.
--Change date and time --Original format --ISO format --First date and time of the month --End of the month
Click here for Java's Utils class.
LocalDateUtils.java
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalAdjusters;
public class LocalDateTimeUtils {
private static final DateTimeFormatter YYYYMM_FORMAT = DateTimeFormatter.ofPattern("yyyyMM");
//Change date and time
public static LocalDateTime getDateTimeAfterOneYear(LocalDateTime dateTime) {
return dateTime.plusYears(1);
}
//Original format
public static String getYearAndMonth(LocalDateTime dateTime) {
return dateTime.format(YYYYMM_FORMAT);
}
//ISO format example)2011-12-03
public static String getIsoLocalDate(LocalDateTime dateTime) {
return dateTime.format(DateTimeFormatter.ISO_LOCAL_DATE);
}
//First date and time of the month
public static LocalDateTime getFirstDayDateTime(LocalDateTime dateTime) {
return LocalDateTime.of(dateTime.with(TemporalAdjusters.firstDayOfMonth()).toLocalDate(), LocalTime.MIN);
}
//End of the month
public static LocalDateTime getLastDayDateTime(LocalDateTime dateTime) {
return LocalDateTime.of(dateTime.with(TemporalAdjusters.lastDayOfMonth()).toLocalDate(), LocalTime.MAX);
}
}
Click here for Kotlin extension classes.
LocalDateTime.kt
import java.time.LocalDateTime
import java.time.LocalTime
import java.time.format.DateTimeFormatter
import java.time.temporal.TemporalAdjusters
private val YYYYMM_FORMAT = DateTimeFormatter.ofPattern("yyyyMM")
//Change date and time
fun LocalDateTime.getDateTimeAfterOneYear(): LocalDateTime = plusYears(1)
//Original format
fun LocalDateTime.getYearAndMonth(): String = format(YYYYMM_FORMAT)
//ISO format example)2011-12-03
fun LocalDateTime.getIsoLocalDate(): String = format(DateTimeFormatter.ISO_LOCAL_DATE)
//First date and time of the month
fun LocalDateTime.getFirstDayDateTime(): LocalDateTime = LocalDateTime.of(with(TemporalAdjusters.firstDayOfMonth()).toLocalDate(), LocalTime.MIN)
//End of the month
fun LocalDateTime.getLastDayDateTime(): LocalDateTime = LocalDateTime.of(with(TemporalAdjusters.lastDayOfMonth()).toLocalDate(), LocalTime.MAX)
Recommended Posts