java中的Date和Calendar相关方法

在开发中有一些需求和Date和Calendar有关,所以在这里总结一下这些实现,以后可以直接使用:
1.获取指定日期是星期几, 参数为null时表示获取当前日期是星期几

public static String getWeekOfDate(Date date) {
        String[] weekOfDays = {"星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"};
        Calendar calendar = Calendar.getInstance();
        if (date != null) {
            calendar.setTime(date);
        }
        int w = calendar.get(Calendar.DAY_OF_WEEK) - 1;
        if (w < 0) {
            w = 0;
        }
        return weekOfDays[w];
    }

2.获取本月的第一天(或者当前日期)

public static String currDate(String current) {
        String currdate = "";
        Calendar cal = Calendar.getInstance();
        cal.setTime(new Date());
        if ("1".equals(current)) {    //current=1:表示获取本月的第一天,否则获取当前日期
            cal.set(Calendar.DAY_OF_MONTH, 1);
        }
        currdate = new SimpleDateFormat("yyyy-MM").format(cal.getTime());
        return currdate;
    }

3.查询上个月(上上个月。。。)的第一天和最后一天

public static String findLastMonth(int num) {
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM");

        Calendar cal = Calendar.getInstance();
        GregorianCalendar gcLast = (GregorianCalendar) Calendar.getInstance();
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());

        calendar.add(Calendar.MONTH, num);   //-1:表示上个月  -2:表示上上个月
        Date theDate = calendar.getTime();
        gcLast.setTime(theDate);
        gcLast.set(Calendar.DAY_OF_MONTH, 1);
        String day_first_prevM = df.format(gcLast.getTime());
        StringBuffer str = new StringBuffer().append(day_first_prevM);
        day_first_prevM = str.toString();
        return day_first_prevM;
    }

4.查询当前日期前(后)x天的日期

public static String beforNumberDay(Date date, int day) {
        Calendar c = Calendar.getInstance();
        c.setTime(date);
        c.add(Calendar.DAY_OF_YEAR, day);
        return new SimpleDateFormat("yyyy-MM-dd").format(c.getTime());
    }

5.获取某年度的最后一天

  public static String getYearLastDate(int year, String pattern) {
        Calendar calendar = Calendar.getInstance();
        calendar.clear();
        calendar.set(Calendar.YEAR, year);
        calendar.roll(Calendar.DAY_OF_YEAR, -1);
        Date currYearLast = calendar.getTime();
        return DateFormatUtils.format(currYearLast, pattern);
    }

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值