java处理时间处理的工具类

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import org.apache.commons.lang.time.DateFormatUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

/**
*时间处理的各种工具类
*/
public class DateTimeUtil {

private static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");

private static Logger logger = LoggerFactory.getLogger(DateTimeUtil.class);

/**
 * 获得所需要的日期格式
 *
 * @param date
 * @param format yyyy-MM-dd HH:mm:ss
 * @return
 */
public static Date getFormatDateFromString(String date, String format) {
    SimpleDateFormat formatter = new SimpleDateFormat(format);
    Date formatDate = null;
    try {
        formatDate = formatter.parse(date);
    } catch (ParseException e) {
        e.printStackTrace();
    }
    return formatDate;
}

// public static void main(String[] args) {
// String date="2021-12-02 ";
// Date formatDateFromString = DateTimeUtil.getFormatDateFromString(date, “yyyy-MM-dd”);
// //Thu Dec 02 00:00:00 CST 2021
// System.out.println(formatDateFromString);
// }

/**
 * 获得所需要的日期格式 date+time
 *
 * @param date   只有 yyyy-MM-dd
 * @param format yyyy-MM-dd HH:mm:ss
 * @param time   HH:mm:ss
 * @return
 */
public static Date getFormatDateFromString(String date, String format, String time) {
    SimpleDateFormat formatter = new SimpleDateFormat(format);
    Date formatDate = null;
    try {
        formatDate = formatter.parse(date + " " + time);
    } catch (ParseException e) {
        e.printStackTrace();
    }
    return formatDate;
}

// public static void main(String[] args) {
// String date="2021-12-02 ";
// String time=“12:05:57”;
// Date formatDateFromString = DateTimeUtil.getFormatDateFromString(date, “yyyy-MM-dd HH:mm:ss”,time);
// //Thu Dec 02 12:05:57 CST 2021
// System.out.println(formatDateFromString);
// }

/**
 *转化为特定的时间格式
 * @param date
 * @param format
 * @return
 */
public static String getFormatStringDate(Date date, String format) {
    DateFormat df = new SimpleDateFormat(format);
    return df.format(date);
}

// public static void main(String[] args) {
// //获取当天的时间(开始和结束时间)
// Date today = DateTimeUtil.getToday();
// Date dayEnd = DateTimeUtil.getDayEnd(DateTimeUtil.getToday());
// String formatDateFromString = DateTimeUtil.getFormatStringDate(today, “yyyy-MM-dd HH:mm:ss”);
// String formatDateFromStrings = DateTimeUtil.getFormatStringDate(dayEnd, “yyyy-MM-dd HH:mm:ss”);
// //2021-12-03 00:00:00
// System.out.println(formatDateFromString);
// System.out.println(formatDateFromStrings);
// }

/**
 * 跟当前时间进行比较
 *
 * @param date
 * @param format
 * @return
 */
public static int compareNowDate(Date date, String format) {
    Date now = new Date();
    int result = 0;
    if (getFormatDate(date, format).getTime() > getFormatDate(now, format).getTime()) {
        result = 1;
    }
    return result;
}

public static void main(String[] args) {
// //获取当天的时间(开始时间)
// Date today = DateTimeUtil.getToday();
// //今天的开始时间与当前时间比较,前者大,返回1,否则0
// int formatDateFromString = DateTimeUtil.compareNowDate(today, “yyyy-MM-dd HH:mm:ss”);
// //2021-12-03 00:00:00
// System.out.println(formatDateFromString);

  Date now = new Date();
  String format = DateFormatUtils.format(now, "yyyy-MM-dd HH:mm:ss");
  System.out.println(format);
}

/**
 * 获得所需要的日期格式
 *
 * @param date
 * @param format yyyy-MM-dd HH:mm:ss
 * @return
 */
public static Date getFormatDate(Date date, String format) {
    DateFormat df = new SimpleDateFormat(format);
    Date formatDate = null;
    try {
        formatDate = df.parse(getFormatStringDate(date, format));
    } catch (Exception e) {
        logger.info("日期转换出错" + e.getMessage());
    }
    return formatDate;
}

// public static void main(String[] args) {
// Date now = new Date();
// //今天的开始时间与当前时间比较,前者大,返回1,否则0
// Date formatDateFromString = DateTimeUtil.getFormatDate(now, “yyyy-MM-dd HH:mm:ss”);
// //Fri Dec 03 14:05:12 CST 2021
// System.out.println(formatDateFromString);
// }

/**
 * 获得本月的第一天
 *
 * @return
 */
public static Date getMonthOfFirst() {
    Calendar calendar = Calendar.getInstance();
    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();
}

// public static void main(String[] args) {
// Date monthOfFirst = DateTimeUtil.getMonthOfFirst();
// Date formatDateFromString = DateTimeUtil.getFormatDate(monthOfFirst, “yyyy-MM-dd HH:mm:ss”);
// //Wed Dec 01 00:00:00 CST 2021
// System.out.println(formatDateFromString);
// }

/**
 * 获得下月的第一天
 *
 * @return
 */
public static Date getMonthOfEnd() {
    Calendar calendar = Calendar.getInstance();
    calendar.add(Calendar.MONTH, 1);
    calendar.set(Calendar.DAY_OF_MONTH, 1);
    calendar.set(calendar.HOUR_OF_DAY, 00);
    calendar.set(calendar.MINUTE, 00);
    calendar.set(calendar.SECOND, 00);
    return calendar.getTime();
}

// public static void main(String[] args) {
// Date monthOfEnd = DateTimeUtil.getMonthOfEnd();
// Date formatDateFromString = DateTimeUtil.getFormatDate(monthOfEnd, “yyyy-MM-dd HH:mm:ss”);
// //Sat Jan 01 00:00:00 CST 2022
// System.out.println(formatDateFromString);
// }

/**
 * 获得该周的周一
 *
 * @return
 */
public static Date getWeekOfFirst() {
    Calendar calendar = Calendar.getInstance();
    calendar.set(calendar.HOUR_OF_DAY, 00);
    calendar.set(calendar.MINUTE, 00);
    calendar.set(calendar.SECOND, 00);
    calendar.set(Calendar.DAY_OF_WEEK, 1);
    calendar.add(calendar.DAY_OF_MONTH, 1);
    return calendar.getTime();
}

/**
 * 获得下周的周一
 *
 * @return
 */
public static Date getWeekOfEnd() {
    Calendar calendar = Calendar.getInstance();
    calendar.set(calendar.HOUR_OF_DAY, 00);
    calendar.set(calendar.MINUTE, 00);
    calendar.set(calendar.SECOND, 00);
    calendar.set(Calendar.DAY_OF_WEEK, 1);
    calendar.add(calendar.DAY_OF_MONTH, 8);
    return calendar.getTime();
}

/**
 * 获得当天时间
 *
 * @return
 */
public static Date getToday() {
    Calendar calendar = Calendar.getInstance();
    calendar.set(calendar.HOUR_OF_DAY, 00);
    calendar.set(calendar.MINUTE, 00);
    calendar.set(calendar.SECOND, 00);
    return calendar.getTime();
}

/**
 * 获取明天日期
 *
 * @return
 */
public static Date getTomorrow() {
    Calendar calendar = Calendar.getInstance();
    calendar.add(calendar.DAY_OF_MONTH, 1);
    calendar.set(calendar.HOUR_OF_DAY, 00);
    calendar.set(calendar.MINUTE, 00);
    calendar.set(calendar.SECOND, 00);
    return calendar.getTime();
}

/**
 * 获取一天的开始
 *
 * @param now
 * @return
 */
public static Date getDayBegin(Date now) {
    Calendar c = Calendar.getInstance();
    c.setTime(now);
    c.set(Calendar.HOUR_OF_DAY, 00);
    c.set(Calendar.MINUTE, 00);
    c.set(Calendar.SECOND, 00);
    return c.getTime();
}

/**
 * 获取一天的结束
 *
 * @param now
 * @return
 */
public static Date getDayEnd(Date now) {
    Calendar c = Calendar.getInstance();
    c.setTime(now);
    c.set(Calendar.HOUR_OF_DAY, 23);
    c.set(Calendar.MINUTE, 59);
    c.set(Calendar.SECOND, 59);
    return c.getTime();
}

/**
 * 获取传入时间对应的星期一的日期
 *
 * @param now
 * @return
 */
public static Date getWeekBegin(Date now) {

    Calendar c = Calendar.getInstance();
    c.setTime(now);
    c.set(Calendar.DAY_OF_WEEK, c.getActualMinimum(Calendar.DAY_OF_WEEK));
    // 国内一周以星期一作为开始
    c.add(Calendar.DATE, 1);
    c.set(Calendar.HOUR_OF_DAY, 00);
    c.set(Calendar.MINUTE, 00);
    c.set(Calendar.SECOND, 00);
    return c.getTime();
}

/**
 * 获取传入时间对应的星期天的日期时间
 *
 * @param now
 * @return
 */
public static Date getWeekEnd(Date now) {

    Calendar c = Calendar.getInstance();
    c.setTime(now);
    c.set(Calendar.DAY_OF_WEEK, c.getActualMaximum(Calendar.DAY_OF_WEEK));
    // 国内一周以星期天作为结束
    c.add(Calendar.DATE, 1);
    c.set(Calendar.HOUR_OF_DAY, 23);
    c.set(Calendar.MINUTE, 59);
    c.set(Calendar.SECOND, 59);
    return c.getTime();
}

/**
 * 获取传入时间对应的月初日期
 *
 * @param now
 * @return
 */
public static Date getMonthBegin(Date now) {

    Calendar c = Calendar.getInstance();
    c.setTime(now);
    c.set(Calendar.DAY_OF_MONTH, c.getActualMinimum(Calendar.DAY_OF_MONTH));
    c.set(Calendar.HOUR_OF_DAY, 00);
    c.set(Calendar.MINUTE, 00);
    c.set(Calendar.SECOND, 00);
    return c.getTime();
}

/**
 * 获取传入时间对应的月末日期
 *
 * @param now
 * @return
 */
public static Date getMonthEnd(Date now) {

    Calendar c = Calendar.getInstance();
    c.setTime(now);
    c.set(Calendar.DAY_OF_MONTH, c.getActualMaximum(Calendar.DAY_OF_MONTH));
    c.set(Calendar.HOUR_OF_DAY, 23);
    c.set(Calendar.MINUTE, 59);
    c.set(Calendar.SECOND, 59);
    return c.getTime();
}

/**
 * 获取某个时间后几天的时间
 *
 * @param sourceTime 时间
 * @param days       x天后提交
 * @return
 */
public static Date getAfterDateTime(Date sourceTime, int days) {

    Calendar calendar = Calendar.getInstance();
    calendar.setTime(sourceTime);
    calendar.add(Calendar.DATE, days);

    return calendar.getTime();
}

/**
 * 获得两者的时间差
 * @param start
 * @param end
 * @return
 */
public static long getTimeDifference(Date start, Date end) {
    return end.getTime() - start.getTime();
}

/**
 * date 转换成String类型
 * @param dateDate
 * @param format
 * @return
 */
public static String dateToStr(Date dateDate, String format) {
    SimpleDateFormat formatter = new SimpleDateFormat(format);
    String dateString = formatter.format(dateDate);
    return dateString;
}

// public static void main(String[] args) {
// Date today = DateTimeUtil.getToday();
// String todays = DateTimeUtil.dateToStr(today, “yyyy-MM-dd”);
// //2021-12-03
// System.out.println(todays);
// }

/**
 * String 类型转换成date类型
 * @param strDate
 * @return
 */
public static Date strToDateLong(String strDate) {
    SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    ParsePosition pos = new ParsePosition(0);
    Date strtodate = formatter.parse(strDate, pos);
    return strtodate;
}

// public static void main(String[] args) {
// String day=“2021-12-02 15:14:05”;
// //2021-12-02 15:14:05
// System.out.println(day);
// Date date = DateTimeUtil.strToDateLong(day);
// //Thu Dec 02 15:14:05 CST 2021
// System.out.println(date);
// }

/**
 * 获取某个时间前几天的时间
 * @param sourceTime
 * @param days
 * @return
 */
public static Date getBeforeDateTime(Date sourceTime, int days) {

    Calendar calendar = Calendar.getInstance();
    calendar.setTime(sourceTime);
    calendar.add(Calendar.DATE, -days);
    return calendar.getTime();
}

// public static void main(String[] args) {
// /**
// * new Date(): Fri Dec 03 15:13:45 CST 2021
// * beforeDateTime: Thu Dec 02 15:13:45 CST 2021
// * format: 2021-12-02 15:13:45
// */
// System.out.println("当前日期是: "+new Date());
// Date beforeDateTime = DateTimeUtil.getBeforeDateTime(new Date(), 1);
// System.out.println("当前日期的前一天的时间类型是: "+beforeDateTime);
// String format = DateFormatUtils.format(DateTimeUtil.getBeforeDateTime(new Date(), 1), “yyyy-MM-dd HH:mm:ss”);
// System.out.println("当前日期的前一天转成字符串类型是: "+format);
// }

/**
 * JAVA8 时间的格式化
 */
public static  String getFormatTime(LocalDateTime now){
    DateTimeFormatter deateTimeFormattrt= DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
    return deateTimeFormattrt.format(now);
}

// public static void main(String[] args) {
// /**
// * 2021-12-03T15:18:27.499
// * 2021-12-03 15:18:27
// */
// LocalDateTime now = LocalDateTime.now();
// System.out.println(now);
// String formatTime = DateTimeUtil.getFormatTime(now);
// System.out.println(formatTime);
// }

/**
 * 根据配置项的天数获取当前日期几天后的日期(Java8)
 */
public  static  String getOtherDay(int allowDay){
    LocalDateTime now =LocalDateTime.now();
    LocalDateTime localDateTime = now.plusDays(-allowDay);
    return getFormatTime(localDateTime).substring(0,10)+" 00:00:00";
}

// public static void main(String[] args) {
// /**
// * 当前日期是: Fri Dec 03 15:25:36 CST 2021
// * 当前日期往前十天的日期2021-11-23 00:00:00
// * 当前日期往前十天的日期2021-12-13 00:00:00
// */
// System.out.println("当前日期是: "+new Date());
// int whts=10;
// int whtss=-10;
// String otherDay = DateTimeUtil.getOtherDay(whts);
// System.out.println(“当前日期往前十天的日期”+otherDay);
// String otherDays = DateTimeUtil.getOtherDay(whtss);
// System.out.println(“当前日期往后十天的日期”+otherDays);
// }

/**
 * getFormatDateString
 */
public static  String getFormatDateString(String time){
    String format="";
    switch (time.length()){
        case 10:
            format="yyyy-MM-dd";
            break;
        case 22:
            format="yyyy-MM-dd HH:mm:ss.SS";
            break;
        case 21:
            format="yyyy-MM-dd HH:mm:ss.S";
            break;
        case 19:
            format="yyyy-MM-dd HH:mm:ss";
            break;
        default:
            format="yyyy-MM-dd HH:mm:ss.SSS";
            break;
    }
    return format;
}

/**
 * 获取时间戳
 * date(yyyy-MM-dd HH:mm:ss.SSS)
 */
public static long getTimStamp(String date){
    Date parse=null;
    try {
        SimpleDateFormat dateformats = new SimpleDateFormat(getFormatDateString(date));
        parse=dateformats.parse(date);
    }catch (Exception e){
        logger.error("=====时间解析错误=====");
        throw new CommonException("时间解析错误");
    }
    return parse.getTime();
}

// public static void main(String[] args) {
// /**
// * day:2021-10-12
// * timStamp:1633968000000
// */
// String day=“2021-10-12”;
// System.out.println(“day”+day);
// long timStamp = DateTimeUtil.getTimStamp(day);
// System.out.println(“timStamp”+timStamp);
// }

/**
 * 时间戳转换时间并格式化时间
 * @param : 时间戳
 * @return :
 */
public static String getTimeByStamp(long stamp){
    Date date=new Date(stamp);
    String format = sdf.format(date);
    return  format;
}

// public static void main(String[] args) {
// /**
// * day:163396800
// * timStamp:1970-01-03 05:23:16.800
// */
// long day;
// day = 163396800;
// System.out.println(“day:”+day);
// String timStamp = DateTimeUtil.getTimeByStamp(day);
// System.out.println(“timStamp:”+timStamp);
// }

/**
 * 根据出生的日期返回年龄
 */
public  static int getAgetByBirth(String birthDay){
    Date formatDate=null;
    try {
         formatDate = new SimpleDateFormat("yyyy-mm-dd").parse(birthDay);
    }catch (ParseException e){
        e.printStackTrace();
    }
    int age;
    Calendar instance = Calendar.getInstance();
    int yearNow = instance.get(Calendar.YEAR);
    int monthNow = instance.get(Calendar.MONTH);
    int dateNow = instance.get(Calendar.DAY_OF_MONTH);
    instance.setTime(formatDate);
    int yearBirth = instance.get(Calendar.YEAR);
    int monthBirth = instance.get(Calendar.MONTH);
    int dateBirth = instance.get(Calendar.DAY_OF_MONTH);
    age=yearNow- yearBirth;
    if (monthNow<=monthBirth){
        if (monthNow==monthBirth){
            if (dateNow<dateBirth){
                age--;
            }else {
                age++;
            }
        }
    }
    return age;
}

// public static void main(String[] args) {
// String age=“2021-12-02”;
// int agetByBirth = DateTimeUtil.getAgetByBirth(age);
// System.out.println(agetByBirth);
// }

/**
 * 日期格式转换
 */
public static String transDateFormats(String fromFormat,String toFormat,String date){
    try {
        Date parse = new SimpleDateFormat(fromFormat).parse(date);
        date=new SimpleDateFormat(toFormat).format(parse);
    } catch (ParseException e) {
      logger.info("日期转换失败,日期原格式为{},转换后的格式为{},日期字符串为{}",fromFormat,toFormat,date);
    }
    return date;
}

// public static void main(String[] args) {
// /**
// * 2020/11/02
// */
// String day=“2021-12-02”;
// String yyyyMMdd = DateTimeUtil.transDateFormats(“yyyyMMdd”, “yyyy/MM/dd”, day);
// System.out.println(yyyyMMdd);
// }

/**
 *获取当前同时间段的前几天的时间
 */
public static String getBeforDateTimeString(String sourceTime,String format,int days){
    Date stringDate = DateTimeUtil.getFormatDateFromString(sourceTime, format);
    Calendar calendar = Calendar.getInstance();
    calendar.setTime(stringDate);
    calendar.add(Calendar.DATE,-days);
    return DateTimeUtil.getFormatStringDate(calendar.getTime(),format);
}

// public static void main(String[] args) {
// /**
// * 2021-11-30 15:12:05
// * 2021-11-30 15:12:05.459
// */
// String day=“2021-12-02 15:12:05”;
// String timestring = DateTimeUtil.getBeforDateTimeString(day, “yyyy-MM-dd HH:mm:ss”, 2);
// System.out.println(timestring);
// String days=“2021-12-02 15:12:05.459”;
// String beforDateTimeString = DateTimeUtil.getBeforDateTimeString(days, “yyyy-MM-dd HH:mm:ss.SSS”, 2);
// System.out.println(beforDateTimeString);
// }

}

package com.hexiang.utils; /** * @(#)DateUtil.java * * * @author kidd * @version 1.00 2007/8/8 */ import java.util.*; import java.text.*; import java.sql.Timestamp; public class DateUtils { /** * 时间范围:年 */ public static final int YEAR = 1; /** * 时间范围:季度 */ public static final int QUARTER = 2; /** * 时间范围:月 */ public static final int MONTH = 3; /** * 时间范围:旬 */ public static final int TENDAYS = 4; /** * 时间范围:周 */ public static final int WEEK = 5; /** * 时间范围:日 */ public static final int DAY = 6; /* 基准时间 */ private Date fiducialDate = null; private Calendar cal = null; private DateUtils(Date fiducialDate) { if (fiducialDate != null) { this.fiducialDate = fiducialDate; } else { this.fiducialDate = new Date(System.currentTimeMillis()); } this.cal = Calendar.getInstance(); this.cal.setTime(this.fiducialDate); this.cal.set(Calendar.HOUR_OF_DAY, 0); this.cal.set(Calendar.MINUTE, 0); this.cal.set(Calendar.SECOND, 0); this.cal.set(Calendar.MILLISECOND, 0); this.fiducialDate = this.cal.getTime(); } /** * 获取DateHelper实例 * * @param fiducialDate * 基准时间 * @return Date */ public static DateUtils getInstance(Date fiducialDate) { return new DateUtils(fiducialDate); } /** * 获取DateHelper实例, 使用当前时间作为基准时间 * * @return Date */ public static DateUtils getInstance() { return new DateUtils(null); } /** * 获取年的第一天 * * @param offset * 偏移量 * @return Date */ public Date getFirstDayOfYear(int offset) { cal.setTime(this.fiducialDate); cal.set(Calendar.YEAR, cal.get(Calendar.YEAR) + offset); cal.set(Calendar.MONTH, Calendar.JANUARY); cal.set(Calendar.DAY_OF_MONTH, 1); return cal.getTime(); } /** * 获取年的最后一天 * * @param offset * 偏移量 * @return Date */ public Date getLastDayOfYear(int offset) { cal.setTime(this.fiducialDate); cal.set(Calendar.YEAR, cal.get(Calendar.YEAR) + offset); cal.set(Calendar.MONTH, Calendar.DECEMBER); cal.set(Calendar.DAY_OF_MONTH, 31); return cal.getTime(); } /** * 获取季度的第一天 * * @param offset * 偏移量 * @return Date */ public Date getFirstDayOfQuarter(int offset) { cal.setTime(this.fiducialDate); cal.add(Calendar.MONTH, offset * 3); int mon = cal.get(Calendar.MONTH); if (mon >= Calendar.JANUARY && mon = Calendar.APRIL && mon = Calendar.JULY && mon = Calendar.OCTOBER && mon = Calendar.JANUARY && mon = Calendar.APRIL && mon = Calendar.JULY && mon = Calendar.OCTOBER && mon = 21) { day = 21; } else if (day >= 11) { day = 11; } else { day = 1; } if (offset > 0) { day = day + 10 * offset; int monOffset = day / 30; day = day % 30; cal.add(Calendar.MONTH, monOffset); cal.set(Calendar.DAY_OF_MONTH, day); } else { int monOffset = 10 * offset / 30; int dayOffset = 10 * offset % 30; if ((day + dayOffset) > 0) { day = day + dayOffset; } else { monOffset = monOffset - 1; day = day - dayOffset - 10; } cal.add(Calendar.MONTH, monOffset); cal.set(Calendar.DAY_OF_MONTH, day); } return cal.getTime(); } /** * 获取旬的最后一天 * * @param offset * 偏移量 * @return Date */ public Date getLastDayOfTendays(int offset) { Date date = getFirstDayOfTendays(offset + 1); cal.setTime(date); cal.add(Calendar.DAY_OF_MONTH, -1); return cal.getTime(); } /** * 获取周的第一天(MONDAY) * * @param offset * 偏移量 * @return Date */ public Date getFirstDayOfWeek(int offset) { cal.setTime(this.fiducialDate); cal.add(Calendar.DAY_OF_MONTH, offset * 7); cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY); return cal.getTime(); } /** * 获取周的最后一天(SUNDAY) * * @param offset * 偏移量 * @return Date */ public Date getLastDayOfWeek(int offset) { cal.setTime(this.fiducialDate); cal.add(Calendar.DAY_OF_MONTH, offset * 7); cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY); cal.add(Calendar.DAY_OF_MONTH, 6); return cal.getTime(); } /** * 获取指定时间范围的第一天 * * @param dateRangeType * 时间范围类型 * @param offset * 偏移量 * @return Date */ public Date getFirstDate(int dateRangeType, int offset) { return null; } /** * 获取指定时间范围的最后一天 * * @param dateRangeType * 时间范围类型 * @param offset * 偏移量 * @return Date */ public Date getLastDate(int dateRangeType, int offset) { return null; } /** * 根据日历的规则,为基准时间添加指定日历字段的时间量 * * @param field * 日历字段, 使用Calendar类定义的日历字段常量 * @param offset * 偏移量 * @return Date */ public Date add(int field, int offset) { cal.setTime(this.fiducialDate); cal.add(field, offset); return cal.getTime(); } /** * 根据日历的规则,为基准时间添加指定日历字段的单个时间单元 * * @param field * 日历字段, 使用Calendar类定义的日历字段常量 * @param up * 指定日历字段的值的滚动方向。true:向上滚动 / false:向下滚动 * @return Date */ public Date roll(int field, boolean up) { cal.setTime(this.fiducialDate); cal.roll(field, up); return cal.getTime(); } /** * 把字符串转换为日期 * * @param dateStr * 日期字符串 * @param format * 日期格式 * @return Date */ public static Date strToDate(String dateStr, String format) { Date date = null; if (dateStr != null && (!dateStr.equals(""))) { DateFormat df = new SimpleDateFormat(format); try { date = df.parse(dateStr); } catch (ParseException e) { e.printStackTrace(); } } return date; } /** * 把字符串转换为日期,日期的格式为yyyy-MM-dd HH:ss * * @param dateStr * 日期字符串 * @return Date */ public static Date strToDate(String dateStr) { Date date = null; if (dateStr != null && (!dateStr.equals(""))) { if (dateStr.matches("\\d{4}-\\d{1,2}-\\d{1,2}")) { dateStr = dateStr + " 00:00"; } else if (dateStr.matches("\\d{4}-\\d{1,2}-\\d{1,2} \\d{1,2}")) { dateStr = dateStr + ":00"; } else { System.out.println(dateStr + " 格式不正确"); return null; } DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:ss"); try { date = df.parse(dateStr); } catch (ParseException e) { e.printStackTrace(); } } return date; } /** * 把日期转换为字符串 * * @param date * 日期实例 * @param format * 日期格式 * @return Date */ public static String dateToStr(Date date, String format) { return (date == null) ? "" : new SimpleDateFormat(format).format(date); } public static String dateToStr(Date date) { return (date == null) ? "" : new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(date); } /** * 取得当前日期 年-月-日 * * @return Date */ public static String getCurrentDate() { DateFormat f = new SimpleDateFormat("yyyy-MM-dd"); return f.format(Calendar.getInstance().getTime()); } public static void main(String[] args) { DateUtils dateHelper = DateUtils.getInstance(); /* Year */ for (int i = -5; i <= 5; i++) { System.out.println("FirstDayOfYear(" + i + ") = " + dateHelper.getFirstDayOfYear(i)); System.out.println("LastDayOfYear(" + i + ") = " + dateHelper.getLastDayOfYear(i)); } /* Quarter */ for (int i = -5; i <= 5; i++) { System.out.println("FirstDayOfQuarter(" + i + ") = " + dateHelper.getFirstDayOfQuarter(i)); System.out.println("LastDayOfQuarter(" + i + ") = " + dateHelper.getLastDayOfQuarter(i)); } /* Month */ for (int i = -5; i <= 5; i++) { System.out.println("FirstDayOfMonth(" + i + ") = " + dateHelper.getFirstDayOfMonth(i)); System.out.println("LastDayOfMonth(" + i + ") = " + dateHelper.getLastDayOfMonth(i)); } /* Week */ for (int i = -5; i <= 5; i++) { System.out.println("FirstDayOfWeek(" + i + ") = " + dateHelper.getFirstDayOfWeek(i)); System.out.println("LastDayOfWeek(" + i + ") = " + dateHelper.getLastDayOfWeek(i)); } /* Tendays */ for (int i = -5; i <= 5; i++) { System.out.println("FirstDayOfTendays(" + i + ") = " + dateHelper.getFirstDayOfTendays(i)); System.out.println("LastDayOfTendays(" + i + ") = " + dateHelper.getLastDayOfTendays(i)); } } /** * 取当前日期的字符串形式,"XXXX年XX月XX日" * * @return java.lang.String */ public static String getPrintDate() { String printDate = ""; Calendar calendar = Calendar.getInstance(); calendar.setTime(new Date()); printDate += calendar.get(Calendar.YEAR) + "年"; printDate += (calendar.get(Calendar.MONTH) + 1) + "月"; printDate += calendar.get(Calendar.DATE) + "日"; return printDate; } /** * 将指定的日期字符串转化为日期对象 * * @param dateStr * 日期字符串 * @return java.util.Date */ public static Date getDate(String dateStr, String format) { if (dateStr == null) { return new Date(); } if (format == null) { format = "yyyy-MM-dd"; } SimpleDateFormat sdf = new SimpleDateFormat(format); try { Date date = sdf.parse(dateStr); return date; } catch (Exception e) { return null; } } /** * 从指定Timestamp中得到相应的日期的字符串形式 日期"XXXX-XX-XX" * * @param dateTime * @return 、String */ public static String getDateFromDateTime(Timestamp dateTime) { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); return sdf.format(dateTime).toString(); } /** * 得到当前时间 return java.sql.Timestamp * * @return Timestamp */ public static Timestamp getNowTimestamp() { long curTime = System.currentTimeMillis(); return new Timestamp(curTime); } }
package com.hexiang.utils; import java.text.SimpleDateFormat; import java.util.*; public class CalendarUtil { public static void main(String args[]) { System.out.println("First day of week is : " + new SimpleDateFormat("yyyy-MM-dd") .format(getFirstDateByWeek(new Date()))); System.out.println("Last day of week is : " + new SimpleDateFormat("yyyy-MM-dd") .format(getLastDateByWeek(new Date()))); System.out.println("First day of month is : " + new SimpleDateFormat("yyyy-MM-dd") .format(getFirstDateByMonth(new Date()))); System.out.println("Last day of month is : " + new SimpleDateFormat("yyyy-MM-dd") .format(getLastDateByMonth(new Date()))); } /** * 获得所在星期的第一天 */ public static Date getFirstDateByWeek(Date date) { Calendar now = Calendar.getInstance(); now.setTime(date); int today = now.get(Calendar.DAY_OF_WEEK); int first_day_of_week = now.get(Calendar.DATE) + 2 - today; // 星期一 now.set(Calendar.DATE, first_day_of_week); return now.getTime(); } /** * 获得所在星期的最后一天 */ public static Date getLastDateByWeek(Date date) { Calendar now = Calendar.getInstance(); now.setTime(date); int today = now.get(Calendar.DAY_OF_WEEK); int first_day_of_week = now.get(Calendar.DATE) + 2 - today; // 星期一 int last_day_of_week = first_day_of_week + 6; // 星期日 now.set(Calendar.DATE, last_day_of_week); return now.getTime(); } /** * 获得所在月份的最后一天 * @param 当前月份所在的时间 * @return 月份的最后一天 */ public static Date getLastDateByMonth(Date date) { Calendar now = Calendar.getInstance(); now.setTime(date); now.set(Calendar.MONTH, now.get(Calendar.MONTH) + 1); now.set(Calendar.DATE, 1); now.set(Calendar.DATE, now.get(Calendar.DATE) - 1); now.set(Calendar.HOUR, 11); now.set(Calendar.MINUTE, 59); now.set(Calendar.SECOND, 59); return now.getTime(); } /** * 获得所在月份的第一天 * @param 当前月份所在的时间 * @return 月份的第一天 */ public static Date getFirstDateByMonth(Date date) { Calendar now = Calendar.getInstance(); now.setTime(date); now.set(Calendar.DATE, 0); now.set(Calendar.HOUR, 12); now.set(Calendar.MINUTE, 0); now.set(Calendar.SECOND, 0); return now.getTime(); } }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

瑾莫

你的鼓励将是我创作的最大动力

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

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

打赏作者

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

抵扣说明:

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

余额充值