在某種場(chǎng)景下我們可能需要獲取當(dāng)前周的開始時(shí)間、結(jié)束時(shí)間,當(dāng)前月的開始時(shí)間、結(jié)束時(shí)間等,給大家分享一個(gè)工具類幫助大家快速去獲取你需要的時(shí)間,便于節(jié)省時(shí)間。文章來源地址http://www.zghlxwxcb.cn/news/detail-771690.html
package org.util; import java.time.*; import java.time.format.DateTimeFormatter; import java.time.temporal.TemporalAdjusters; public class Test { public static void main(String[] args) { // 獲取當(dāng)天日期 LocalDate now = LocalDate.now(); // 當(dāng)天開始時(shí)間 LocalDateTime todayStart = now.atStartOfDay(); // 當(dāng)天結(jié)束時(shí)間 LocalDateTime todayEnd = LocalDateTime.of(now, LocalTime.MAX); // 周一 LocalDate monday = now.with(TemporalAdjusters.previousOrSame(DayOfWeek.MONDAY)); // 周日 LocalDate sunday = now.with(TemporalAdjusters.nextOrSame(DayOfWeek.SUNDAY)); // 本周開始時(shí)間 LocalDateTime weekStart = monday.atStartOfDay(); // 本周結(jié)束時(shí)間 LocalDateTime weekEnd = LocalDateTime.of(sunday, LocalTime.MAX); // 本月1號(hào) LocalDate firstDayOfMonth = now.with(TemporalAdjusters.firstDayOfMonth()); // 本月最后一天 LocalDate lastDayOfMonth = now.with(TemporalAdjusters.lastDayOfMonth()); // 本月1號(hào)的開始時(shí)間 LocalDateTime firstDayOfMonthStart = firstDayOfMonth.atStartOfDay(); // 本月最后一天的最后時(shí)間 LocalDateTime firstDayOfMonthEnd = LocalDateTime.of(lastDayOfMonth, LocalTime.MAX); // 今年第一天 LocalDate beginTime = LocalDate.now().with(TemporalAdjusters.firstDayOfYear()); // 今年最后一天 LocalDate endTiime = LocalDate.now().with(TemporalAdjusters.lastDayOfYear()); //獲取前一天日期 LocalDate yesterday2 = LocalDate.now().minusDays(1); DateTimeFormatter pattern = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); System.out.println("當(dāng)天開始時(shí)間 = " + todayStart.format(pattern)); System.out.println("當(dāng)天結(jié)束時(shí)間 = " + todayEnd.format(pattern)); System.out.println("本周開始時(shí)間 = " + weekStart.format(pattern)); System.out.println("本周結(jié)束時(shí)間 = " + weekEnd.format(pattern)); System.out.println("本月開始時(shí)間 = " + firstDayOfMonthStart.format(pattern)); System.out.println("本月結(jié)束時(shí)間 = " + firstDayOfMonthEnd.format(pattern)); } }
文章來源:http://www.zghlxwxcb.cn/news/detail-771690.html
到了這里,關(guān)于【知識(shí)分享】Java獲取當(dāng)前周的開始時(shí)間結(jié)束時(shí)間的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!