java 得到指定日期的起始時間

項目中常常會遇到得到指定日期的起止時間,如得到當月的起始時間和結束時間。以前已經講過在前段的實現。如今咱們看看在java後端如何實現。java

主要藉助Calendar類實現。後端

得到一日的起始和結束時間:get

Calendar now = Calendar.getInstance();
now.setTime(date);
now.set(Calendar.HOUR_OF_DAY, 0);
now.set(Calendar.MINUTE, 0);
now.set(Calendar.SECOND, 0);
now.set(Calendar.MILLISECOND, 0);
Date beginOfDay = now.getTime();
now.add(Calendar.DAY_OF_YEAR, 1);
now.add(Calendar.MILLISECOND, -1);
Date endOfDay = now.getTime();

Mon Jan 07 00:00:00 CST 2019
Mon Jan 07 23:59:59 CST 2019date

得到一週的起始和結束時間:im

Calendar now = Calendar.getInstance();
now.setTime(date);
now.set(Calendar.DAY_OF_WEEK, 1);
now.set(Calendar.HOUR_OF_DAY, 0);
now.set(Calendar.MINUTE, 0);
now.set(Calendar.SECOND, 0);
now.set(Calendar.MILLISECOND, 0);
Date beginOfWeek = now.getTime();
now.add(Calendar.WEEK_OF_YEAR, 1);
now.add(Calendar.MILLISECOND, -1);
Date endOfWeek = now.getTime();

Sun Jan 06 00:00:00 CST 2019
Sat Jan 12 23:59:59 CST 2019項目

得到一個月的起始和結束時間:時間

Calendar now = Calendar.getInstance();
now.setTime(date);
now.set(Calendar.DAY_OF_MONTH, 1);
now.set(Calendar.HOUR_OF_DAY, 0);
now.set(Calendar.MINUTE, 0);
now.set(Calendar.SECOND, 0);
now.set(Calendar.MILLISECOND, 0);
Date beginOfMon = now.getTime();
now.add(Calendar.MONTH, 1);
now.add(Calendar.MILLISECOND, -1);
Date endOfMon = now.getTime();

Tue Jan 01 00:00:00 CST 2019
Thu Jan 31 23:59:59 CST 2019日期

得到一年的起始和結束時間:

Calendar now = Calendar.getInstance();
now.setTime(date);
now.set(Calendar.MONTH, 0);
now.set(Calendar.DAY_OF_YEAR, 1);
now.set(Calendar.HOUR_OF_DAY, 0);
now.set(Calendar.MINUTE, 0);
now.set(Calendar.SECOND, 0);
now.set(Calendar.MILLISECOND, 0);
Date beginOfYear = now.getTime();
now.add(Calendar.YEAR, 1);
now.add(Calendar.MILLISECOND, -1);
Date endOfYear = now.getTime();

Tue Jan 01 00:00:00 CST 2019 Tue Dec 31 23:59:59 CST 2019

相關文章
相關標籤/搜索