zoukankan      html  css  js  c++  java
  • Calendar类常用需求方法

    经常处理一些日期相关的信息,Calendar类是处理日期的常用类,写下几个方法,不用重复造轮子了。

    1.求上一天,下一天的日期

    Date now = new Date();
    Calendar c = Calendar.getInstance();
    c.setTime(now);
    c.add(Calendar.DAY_OF_MONTH, -1);  // 下一天,上一天-1改为1
    Date yesterday = c.getTime();
    SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
    System.out.println(sdf.format(yesterday));

    2.给定开始时间和结束时间,输出中间每一天

    Date now = new Date();
    Calendar c = Calendar.getInstance();
    SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
    String begin = "20161201";
    String end = "20170210";
    try {
    Date begin_date = sdf.parse(begin);
    Date end_date = sdf.parse(end);

    List<Date> lDate = new ArrayList<Date>();
    lDate.add(begin_date);
    Calendar calBegin = Calendar.getInstance();
    // 使用给定的 Date 设置此 Calendar 的时间
    calBegin.setTime(begin_date);
    Calendar calEnd = Calendar.getInstance();
    // 使用给定的 Date 设置此 Calendar 的时间
    calEnd.setTime(end_date);
    // 测试此日期是否在指定日期之后
    while (end_date.after(calBegin.getTime())) {
    // 根据日历的规则,为给定的日历字段添加或减去指定的时间量
    calBegin.add(Calendar.DAY_OF_MONTH, 1);
    lDate.add(calBegin.getTime());
    }

    for (Date date : lDate) {
    String format = sdf.format(date);
    System.out.println(format);
    }

    3.compareTo()方法,比较两个Calendar的日期谁在前谁在后,在之前的话为-1,相同为0,在之后为1

    4.Calendar类的before和after方法,参数都为Calendar才能正确比较

  • 相关阅读:
    06-引用类初始化问题
    mac系统下Eclipse + pydev配置python Interpreter
    spring 整合mongodb报NoSuchMethodError错误
    mybatis在spring(Controller) 中的事务配置问题
    IT经理工作职责
    postman具体讲解
    用Jmeter进行接口测试及乱码问题
    购物车测试点
    web测试流程的总结及关注点
    fiddler常见的应用场景
  • 原文地址:https://www.cnblogs.com/sansamh/p/6393072.html
Copyright © 2011-2022 走看看