Kotlin中如何进行天级日期的相关操作?
Java天级日期获取与日期操作实现方案
以下基于Java不同版本给出对应的实现方式,无需手动处理System.currentTimeMillis()的毫秒级转换逻辑即可满足需求:
Java 8及以上版本(官方推荐)
Java 8引入的java.time包解决了旧版日期API的线程安全、易用性问题,是目前的最优选择:
获取dd.MM.yyyy格式的天级当前日期
import java.time.LocalDate; import java.time.format.DateTimeFormatter; // 定义目标日期格式 DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("dd.MM.yyyy"); // 获取天级粒度的当前日期,无时分秒、毫秒信息 LocalDate currentDate = LocalDate.now(); // 转换为指定格式的字符串 String formattedDate = currentDate.format(dateFormatter); // 输出示例:22.11.2021 System.out.println(formattedDate);
如果需要从已有的System.currentTimeMillis()返回的毫秒值转换为天级日期,可按以下方式处理:
import java.time.Instant; import java.time.ZoneId; long currentMillis = System.currentTimeMillis(); LocalDate dateFromMillis = Instant.ofEpochMilli(currentMillis) .atZone(ZoneId.systemDefault()) .toLocalDate(); String formattedDate = dateFromMillis.format(dateFormatter);
日期加减操作
LocalDate原生提供了日期增减的方法,直接调用即可:
// 向后累加14天 LocalDate dateAfter14Days = currentDate.plusDays(14); // 格式化为目标格式 String formattedAfter14Days = dateAfter14Days.format(dateFormatter); // 其他常用操作示例 LocalDate dateBefore7Days = currentDate.minusDays(7); // 向前减7天 LocalDate dateAfter2Months = currentDate.plusMonths(2); // 向后加2个月 LocalDate dateAfter1Year = currentDate.plusYears(1); // 向后加1年
Java 8以下旧版本
旧版本可使用Calendar和SimpleDateFormat实现,但注意SimpleDateFormat是非线程安全类,多线程场景下需单独处理:
import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; // 定义目标日期格式 SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy"); // 获取当前日期 Date currentDate = new Date(); String formattedDate = sdf.format(currentDate); // 向后累加14天 Calendar calendar = Calendar.getInstance(); calendar.setTime(currentDate); calendar.add(Calendar.DAY_OF_YEAR, 14); Date dateAfter14Days = calendar.getTime(); String formattedAfter14Days = sdf.format(dateAfter14Days);
内容的提问来源于stack exchange,提问作者Ralf Wickum
相关产品推荐
相关产品推荐

