Java基础之日期时间

java.util 包提供了 Date 类来封装当前的日期和时间。

项目中常用的时间:

TimeUtil工具类

package com.shanyue.syonehealth.utils;

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

public class TimeUtil {

    //获取当前系统时间
    public static String getSystemTime(String sfm) {
        if (sfm == null) sfm = "yyyy-MM-dd";
        Date date = new Date();
        SimpleDateFormat forager = new SimpleDateFormat(sfm);
        return forager.format(date);
    }

    //获取当前周几
    public static String getWeekOfDate(Date date) {
        String[] weekDays = { "星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六" };
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        int w = cal.get(Calendar.DAY_OF_WEEK) - 1;
        if (w < 0)
            w = 0;
        return weekDays[w];
    }

    //获取当日几个月后前后时间
    public  static String getMonthOfDate(int m,String sfm) {
        if (sfm == null) sfm = "yyyy-MM-dd";
        Calendar date = Calendar.getInstance();
        date.setTime(new Date());
        date.add(Calendar.MONTH,m);
        SimpleDateFormat formatter = new SimpleDateFormat(sfm);
        return formatter.format(date.getTime());
    }

    //获取当日几天前后时间
    public  static String getAfterDay(int m,String sfm) {
        if (sfm == null) sfm = "yyyy-MM-dd";
        Calendar date = Calendar.getInstance();
        date.setTime(new Date());
        date.add(Calendar.DATE,m);
        SimpleDateFormat formatter = new SimpleDateFormat(sfm);
        return formatter.format(date.getTime());

    }

    // 获取当月1号
    public static  String  getNowMonth(String fmt) {
        if(fmt==null)fmt="yyyy-MM-dd";
        Calendar date = Calendar.getInstance();
        date.set(Calendar.DAY_OF_MONTH, 1);
        SimpleDateFormat formatter = new SimpleDateFormat(fmt);
        return formatter.format(date.getTime());
    }
    //获取当月最后一天
    public static  String  getFinallyMonth(String fmt) {
        int maxCurrentMonthDay;
        if(fmt==null)fmt="yyyy-MM-dd";
        Calendar date = Calendar.getInstance();
        maxCurrentMonthDay = date.getActualMaximum(Calendar.DAY_OF_MONTH);
        date.set(Calendar.DAY_OF_MONTH, maxCurrentMonthDay);
        SimpleDateFormat formatter = new SimpleDateFormat(fmt);
        return formatter.format(date.getTime());
    }

    // 获取当前季度
    public static String getQuarter() {
        String str = getSystemTime("MM");
        switch (str) {
            case "01":
            case "02":
            case "03":
                return "1";
            case "04":
            case "05":
            case "06":
                return "2";
            case "07":
            case "08":
            case "09":
                return "3";
            default:
                return "4";
        }
    }
    //获取今日是当年的第几周
    public static String getWeek() {
        Calendar calendar = Calendar.getInstance();
        int weekOfYear = calendar.get(Calendar.WEEK_OF_YEAR);
        return String.valueOf(weekOfYear);
    }

    //时间date1是否在时间date2之前
    public static boolean isDateBefore(String date1,String date2) {
        return date1.compareTo(date2)>=0;
    }

   //哪一年中哪一周
    public static int getYearWeek() {
        Calendar date = Calendar.getInstance();
        int week = date.get(Calendar.WEEK_OF_YEAR);
        int year =date.get(Calendar.YEAR);
        return year*100+week;
    }
    //哪天后几个月后的那天
    public static String getDateBeforeMonth(String currentDate, int beforeMonth) {
        int year = Integer.parseInt(currentDate.substring(0, 4));
        int Month = Integer.parseInt(currentDate.substring(5, 7));
        int date = Integer.parseInt(currentDate.substring(8));
        GregorianCalendar g = new GregorianCalendar(year, Month, date);
        g.add(Calendar.MONTH, beforeMonth);
        int m = g.get(Calendar.MONTH);
        if (m == 0)
            m = 12;
        return g.get(Calendar.YEAR) + "-" + m + "-" + g.get(Calendar.DATE);
    }

   //日期转时间戳:yyyy-MM-dd
    public static long getStrToLong(String str,String sfm) {
        if (sfm == null) sfm = "yyyy-MM-dd";
        Calendar c = Calendar.getInstance();
        try {
            c.setTime(new SimpleDateFormat(sfm).parse(str));
            return c.getTimeInMillis();
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return 0L;
    }

    //获取当前时间戳
    public static long getDateToLong(Date dt){
        return dt.getTime();
    }
    // 前一年中本月
    public static Integer getMonth() {
        Date currentTime = new Date();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyyMM");
        String dateString = formatter.format(currentTime);
        return Integer.valueOf(dateString);
    }
    /**
     * 计算两个日期之间相差的天数
     * @param smdate 较小的时间
     * @param bdate  较大的时间
     * @return 相差天数
     * @throws ParseException
     */
    public static int daysBetween(Date smdate,Date bdate) throws ParseException
    {
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
        smdate=sdf.parse(sdf.format(smdate));
        bdate=sdf.parse(sdf.format(bdate));
        Calendar cal = Calendar.getInstance();
        cal.setTime(smdate);
        long time1 = cal.getTimeInMillis();
        cal.setTime(bdate);
        long time2 = cal.getTimeInMillis();
        long between_days=(time2-time1)/(1000*3600*24);
        return Integer.parseInt(String.valueOf(between_days));
    }

    /**
     *字符串的日期格式的计算
     */
    public static int daysBetween(String smdate,String bdate)  {

        try{
            SimpleDateFormat sdf=new SimpleDateFormat("yyyyMMdd");
            Calendar cal = Calendar.getInstance();
            cal.setTime(sdf.parse(smdate));
            long time1 = cal.getTimeInMillis();
            cal.setTime(sdf.parse(bdate));
            long time2 = cal.getTimeInMillis();
            long between_days=(time2-time1)/(1000*3600*24);

            return Integer.parseInt(String.valueOf(between_days));
        }
        catch(ParseException e){
            return -1;
        }
    }
    public static int daysBetween(Long smdate,Long bdate)  {

        try{
            SimpleDateFormat sdf=new SimpleDateFormat("yyyyMMddHHmmss");
            Calendar cal = Calendar.getInstance();
            cal.setTime(sdf.parse(smdate.toString()));
            long time1 = cal.getTimeInMillis();
            cal.setTime(sdf.parse(bdate.toString()));
            long time2 = cal.getTimeInMillis();
            long between_days=(time2-time1)/(1000*3600*24);

            return Integer.parseInt(String.valueOf(between_days));
        }
        catch(ParseException e){
            return -1;
        }
    }
   //今天的前后几天
    public static int afterDay(String date,int day){
        try{
            SimpleDateFormat sdf=new SimpleDateFormat("yyyyMMdd");
            Calendar cal = Calendar.getInstance();
            cal.setTime(sdf.parse(date));
            cal.add(Calendar.DAY_OF_MONTH, day);
            String str= sdf.format(cal.getTime());
            return Integer.parseInt(str);
        }
        catch(ParseException e){
            return -1;
        }
    }
}

测试类:

public static void main(String[] args) {
    //获取系统当前时间 默认格式 yyyy-MM-dd HH:mm:ss
    System.out.println(TimeUtil.getSystemTime(null));
    System.out.println(TimeUtil.getSystemTime("yyyy:MM:dd HH:mm:ss"));
    System.out.println(TimeUtil.getSystemTime("yyyy/MM/dd"));
    //获取当日周几
    System.out.println(TimeUtil.getWeekOfDate(new Date()));
    //获取当日几个月后前后时间
    System.out.println(TimeUtil.getMonthOfDate(1, null));
    System.out.println(TimeUtil.getMonthOfDate(2, "yyyy:MM:dd HH:mm:ss"));
    System.out.println(TimeUtil.getMonthOfDate(-1, "yyyy/MM/dd"));
    //获取当日几天前后时间
    System.out.println(TimeUtil.getAfterDay(8, null));
    System.out.println(TimeUtil.getAfterDay(2, "yyyy:MM:dd HH:mm:ss"));
    System.out.println(TimeUtil.getAfterDay(-1, "yyyy/MM/dd"));
    //获取当月1号
    System.out.println(TimeUtil.getNowMonth(null));
    System.out.println(TimeUtil.getNowMonth("yyyy:MM:dd HH:mm:ss"));
    System.out.println(TimeUtil.getNowMonth("yyyy/MM/dd"));
    //获取当月最后一天
    System.out.println(TimeUtil.getFinallyMonth(null));
    System.out.println(TimeUtil.getFinallyMonth("yyyy:MM:dd HH:mm:ss"));
    System.out.println(TimeUtil.getFinallyMonth("yyyy/MM/dd"));
    //获取当前季度
    System.out.println("第" + TimeUtil.getQuarter() + "季度");
    //获取今日是当年的第几周
    System.out.println("今日是当年的第" + TimeUtil.getWeek() + "周");
    //时间date1是否在时间date2之前
    System.out.println(TimeUtil.isDateBefore(TimeUtil.getFinallyMonth(null), TimeUtil.getSystemTime(null)));
    System.out.println(TimeUtil.isDateBefore(TimeUtil.getSystemTime(null), TimeUtil.getFinallyMonth(null)));
    //哪一年中哪一周
    System.out.println(TimeUtil.getYearWeek());
    //哪天后几个月后的那天
    System.out.println(TimeUtil.getDateBeforeMonth("2021-04-01",5));
    System.out.println(TimeUtil.getDateBeforeMonth("2021-03-31",4));
    //日期转时间戳:yyyy-MM-dd
    System.out.println(TimeUtil.getStrToLong(TimeUtil.getSystemTime("yyyy-MM-dd HH:mm:ss"),"yyyy-MM-dd HH:mm:ss"));
    //获取当前时间戳
    System.out.println(TimeUtil.getDateToLong(new Date()));
    //前一年中本月
    System.out.println(TimeUtil.getMonth());
    //计算两个日期之间相差的天数
    System.out.println(TimeUtil.daysBetween("2021-03-01","2021-03-05"));
    //今天的前后几天
    System.out.println(TimeUtil.afterDay("2021-03-01",5));
    System.out.println(TimeUtil.afterDay("2021-03-01",-5));
}

评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Java之眼

创作不易,一起努力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值