FreeCMS商业版

功能强大、开源、代码通俗易懂、注释详细、面向二次开发友好!

承接网站建设、软件开发、微信开发项目,价格从优,欢迎咨询合作!

FreeCMS商业版V2.8已发布!购买请联系客服QQ 124812878 查看更新日志



在线演示 立即购买 下载免费版 下载商业版用户手册
客服QQ: 124812878 联系电话: 18339991503 Email: freeteam@foxmail.com

Java中calendar的使用 - 流年andrew - ITeye博客

加入收藏夹】     【打印】     【关闭】 来源: 日期:2018-04-23 22:00:07 点击量: 收藏

1.使用calendar取上月最后一天

使用calendar.getActualMaximum(Calendar.DAY_OF_MONTH)取最大值

package com.andrew.code;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

/**
 * CalendarUtil
 *
 * @author andrew
 * @date 2018/4/17.
 */
public class CalendarUtil {

    public static void main(String[] args) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        System.out.println("the last day of last month:" + sdf.format(getLastDayOfLastMonth()));
    }

    /**
     * the last day of last month
     */
    public static Date getLastDayOfLastMonth() {
        Calendar calendar = Calendar.getInstance();
        int month = calendar.get(Calendar.MONTH);
        calendar.set(Calendar.MONTH, month - 1);
        calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMaximum(Calendar.DAY_OF_MONTH));
        calendar.set(Calendar.HOUR_OF_DAY, calendar.getActualMaximum(Calendar.HOUR_OF_DAY));
        calendar.set(Calendar.MINUTE, calendar.getActualMaximum(Calendar.MINUTE));
        calendar.set(Calendar.SECOND, calendar.getActualMaximum(Calendar.SECOND));
        return calendar.getTime();
    }
}

2.使用calendar取当月第一天

使用calendar.set(Calendar.DAY_OF_MONTH, 1);设置最小值

package com.andrew.code;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

/**
 * CalendarUtil
 *
 * @author andrew
 * @date 2018/4/17.
 */
public class CalendarUtil {

    public static void main(String[] args) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        System.out.println("the first day of this month:" + sdf.format(getFirstDayOfThisMonth()));
    }

    /**
     * the first day of this month
     */
    public static Date getFirstDayOfThisMonth() {
        Calendar calendar = Calendar.getInstance();
        int month = calendar.get(Calendar.MONTH);
        calendar.set(Calendar.MONTH, month);
        calendar.set(Calendar.DAY_OF_MONTH, 1);
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        return calendar.getTime();
    }
}

补充说明

(1) 注意calender的变量
MONTH,DAY_OF_MONTH,HOUR_OF_DAY,MINUTE,SECOND
(2) 取最大值,最小值
calendar.set(Calendar.MINUTE, calendar.getActualMaximum(Calendar.MINUTE));
calendar.set(Calendar.MINUTE, 0);



上一条

下一条

相关新闻
自定义表单
本例固定链接: 分享到:
更多