java获取指定年月的开始时间与结束时间

来源:互联网 发布:华新数控螺紋编程 编辑:程序博客网 时间:2024/05/29 17:55

java获取指定年月的开始时间与结束时间


项目中用到mongoldb,操作mongoldb 用的是spring data框架。由于mongoldb java驱动要求的事java类型Date与自己的iso date 类型才能保存,而且mongoldb还没像sql数据库一样,提供对时间的处理函数,而项目中经常利用时间区统计数据,进行计算,所以,时间的计算只能由java层处理了。

package com.doctor.java.time;import java.text.SimpleDateFormat;import java.time.LocalDate;import java.time.LocalDateTime;import java.time.YearMonth;import java.time.ZoneId;import java.time.ZonedDateTime;import java.util.Date;/** * 得到一个月的开始时间与结束时间 ( *  * 返回Date类型,因为mongoDB ) *  * @author sdcuike * * @time 2016年1月2日 下午9:16:11 */public class TimeBeginAndEndOFaMonth {    public static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");    public static void main(String[] args) {        int year = 2016, month = 3;        Date beginTime = getBeginTime(year, month);        System.out.println(sdf.format(beginTime));        Date endTime = getEndTime(year, month);        System.out.println(sdf.format(endTime));    }    public static Date getBeginTime(int year, int month) {        YearMonth yearMonth = YearMonth.of(year, month);        LocalDate localDate = yearMonth.atDay(1);        LocalDateTime startOfDay = localDate.atStartOfDay();        ZonedDateTime zonedDateTime = startOfDay.atZone(ZoneId.of("Asia/Shanghai"));        return Date.from(zonedDateTime.toInstant());    }    public static Date getEndTime(int year, int month) {        YearMonth yearMonth = YearMonth.of(year, month);        LocalDate endOfMonth = yearMonth.atEndOfMonth();        LocalDateTime localDateTime = endOfMonth.atTime(23, 59, 59, 999);        ZonedDateTime zonedDateTime = localDateTime.atZone(ZoneId.of("Asia/Shanghai"));        return Date.from(zonedDateTime.toInstant());    }}


获取一个月的开始时间与结束时间:

2016-03-01 00:00:00

2016-03-31 23:59:59




0 0