java日期处理函数

java中获取本年第一天的日期

public static Timestamp getYearFirstDay() {
Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("GMT+8:00"));// 设置时区~如果使用UTC时区,可以不用设置
int year = calendar.get(Calendar.YEAR);
calendar.clear();
calendar.set(Calendar.YEAR, year);
return new Timestamp(calendar.getTimeInMillis());
}

输出结果:

2016-01-01 00:00:00.0

 

java中获取本周第一天的日期

public static Timestamp getMondayTime() {
        Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("GMT+8:00"));// 设置时区~如果使用UTC时区,可以不用设置
        calendar.setTimeInMillis(System.currentTimeMillis());
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND, 0);
        int dayWeek = calendar.get(Calendar.DAY_OF_WEEK);
        if (1 == dayWeek) { 
            calendar.add(Calendar.DAY_OF_MONTH, -1);
        }
        calendar.setFirstDayOfWeek(Calendar.MONDAY); //设置周一为一周的第一天,否则默认是周日

        int day = calendar.get(Calendar.DAY_OF_WEEK); //一周有多少天
        calendar.add(Calendar.DATE, calendar.getFirstDayOfWeek() - day);
        return new Timestamp(calendar.getTimeInMillis());
    }

 获取上个月的第一天:

// 获取上个月的第一天
    public static Timestamp getFirstDayForLastMonth() {
        Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("GMT+8:00"));
        calendar.add(Calendar.MONTH, -1);
        calendar.set(Calendar.DAY_OF_MONTH, 1);
        return new Timestamp(calendar.getTimeInMillis());
    }

 

 

获取上个月的最后一天:

// 获取上个月的最后一天
    public static Timestamp getLastDayForLastMonth() {
        Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("GMT+8:00"));
        calendar.set(Calendar.DAY_OF_MONTH, 0);
        return new Timestamp(calendar.getTimeInMillis());
    }

 

posted @ 2016-12-14 10:02  SonoFelice  阅读(1343)  评论(0编辑  收藏  举报