DateUtil.java 13.1 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419
package com.skua.modules.guest.util;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.*;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.*;
import java.util.stream.Stream;

/**
 * @author sonin
 * @date 2021/8/18 11:34
 */
public class DateUtil {

    private static DateUtil dateUtil;

    public static DateUtil getInstance() {
        if (dateUtil == null) {
            synchronized (DateUtil.class) {
                if (dateUtil == null) {
                    dateUtil = new DateUtil();
                }
            }
        }
        return dateUtil;
    }


    /***
     * 计算年龄
     * @param birthdate
     * @return
     */
    public static int calculateAge(Date birthdate) {
        LocalDate now = LocalDate.now();
        LocalDate dob = birthdate.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();

        Period period = Period.between(dob, now);
        int age = period.getYears();

        return age;
    }
    /**
     * 转化日期格式
     * @param dateString  要转换的日期字符串
     * @param format  转换后的格式 默认 yyyy-MM-dd
     * @return
     */
    public String convertDateFormat(String  dateString ,String format){
        // 使用 SimpleDateFormat 来定义你想要的日期格式
        SimpleDateFormat formatter = null;

        String formattedDate = null;
        try {
            if(format != null && format.length() >0 ){
                formatter = new SimpleDateFormat(format);
            }else{
                formatter = new SimpleDateFormat("yyyy-MM-dd");
            }
            if(dateString != null && dateString.length() > 0){
                // 将日期字符串转换为 Date 对象
                Date date = formatter.parse(dateString);
                // 再将 Date 对象格式化为字符串
                formattedDate = formatter.format(date);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return formattedDate;
    }

    public String convertDateFormat(Date  date ,String format){
        // 使用 SimpleDateFormat 来定义你想要的日期格式
        SimpleDateFormat formatter = null;

        String formattedDate = null;
        try {
            if(format != null && format.length() >0 ){
                formatter = new SimpleDateFormat(format);
            }else{
                formatter = new SimpleDateFormat("yyyy-MM-dd");
            }
            // 将日期字符串转换为 Date 对象
            // 再将 Date 对象格式化为字符串
            formattedDate = formatter.format(date);
            // 输出结果
            //System.out.println(formattedDate); // 输出: 2024-08-19

        } catch (Exception e) {
            e.printStackTrace();
        }
        return formattedDate;
    }


    /***
     * 获取两个时间的日期
     * @param start
     * @param end
     * @return
     */
    public static List<String> getDaysBetween(String start, String end,String format) {
        List<String> days = new ArrayList<>();
        if(format == null ){
            format = "yyyy-MM-dd";
        }
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern(format);
        // 解析日期
        LocalDate startDate = LocalDate.parse(start, formatter);
        LocalDate endDate = LocalDate.parse(end, formatter);
        LocalDate currentDate = LocalDate.now();//创建一个LocalData对象获取当前日期
        if(endDate.isAfter( currentDate)){
            endDate = currentDate;
        }
        long numOfDaysBetween = ChronoUnit.DAYS.between(startDate, endDate);
        for (int i = 0; i <= numOfDaysBetween; i++) {
            LocalDate date = startDate.plusDays(i);
            days.add(date.toString()); // 格式化为 yyyy-MM
        }
        return days;
    }

    /***
     * 获取月份的天数
     * @param dateTime
     * @param format
     * @return
     */
    public static int getDaysInMonth(String dateTime ,String format ){
        if(format == null ){
            format = "yyyy-MM-dd";
        }
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern(format);
        // 解析日期
        LocalDate date = LocalDate.parse(dateTime, formatter);
        // 获取当前月份的天数
        int daysInMonth = (int) date.lengthOfMonth();
        return daysInMonth;
    }
    /***
     * 获取两个时间的月份
     * @param start
     * @param end
     * @return
     */
    public static List<String> getMonthsBetween(String start, String end,String format) {
        if(format == null ){
            format = "yyyy-MM-dd";
        }
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern(format);
        // 解析日期
        LocalDate startDate = LocalDate.parse(start, formatter);
        LocalDate endDate = LocalDate.parse(end, formatter);
        LocalDate currentDate = LocalDate.now();//创建一个LocalData对象获取当前日期
        if(endDate.isAfter( currentDate)){
            endDate = currentDate;
        }
        List<String> months = new ArrayList<>();
        // 获取起始和结束月份
        YearMonth startMonth = YearMonth.from(startDate);
        YearMonth endMonth = YearMonth.from(endDate);
        // 遍历月份并添加到列表
        YearMonth currentMonth = startMonth;
        while (!currentMonth.isAfter(endMonth)) {
            months.add(currentMonth.toString()); // 格式化为 yyyy-MM
            currentMonth = currentMonth.plusMonths(1);
        }
        return months;
    }

    /**
     *  获取两个日期之间的所有日期 (年月日)
     *
     * @param startTime
     * @param endTime
     * @return
     */
    public static List<String> getBetweenDate(String startTime, String endTime,String format){
        if(format == null ){
            format = "yyyy-MM-dd";
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

        SimpleDateFormat formatSDF = new SimpleDateFormat(format);
        // 声明保存日期集合
        List<String> list = new ArrayList<String>();
        try {
            // 转化成日期类型
            Date startDate = sdf.parse(startTime);
            Date endDate = sdf.parse(endTime);

            Date currentDate = new Date();
            if(currentDate.getTime() < endDate.getTime() ){
                endDate = currentDate;
            }
            //用Calendar 进行日期比较判断
            Calendar calendar = Calendar.getInstance();
            while (startDate.getTime() <= endDate.getTime()){
                // 把日期添加到集合
                list.add(formatSDF.format(startDate));
                // 设置日期
                calendar.setTime(startDate);
                //把日期增加一天
                calendar.add(Calendar.DATE, 1);
                // 获取增加后的日期
                startDate=calendar.getTime();
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return list;
    }

    /**
     * 获取7天日期数据,并指定显示格式
     * @param dateFormat
     * @return
     */
    public List<String> get7Day(String dateFormat) {
        if(dateFormat == null ){
            dateFormat = "yyyy-MM-dd";
        }
        LocalDate today = LocalDate.now();
        List<String> dates = new ArrayList<>();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern(dateFormat);

        for (int i = 0; i < 7; i++) {
            LocalDate date = today.minusDays(i);
            dates.add(date.format(formatter));
        }
        return dates;
    }

    /**
     * 获取今天日期
     *
     * @return
     */
    public String getToday() {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Calendar calendar = Calendar.getInstance();
        return simpleDateFormat.format(calendar.getTime());
    }

    /**
     * 获取本周每天的日期
     *
     * @return
     */
    public List<String> getWeek() {
        List<String> weekList = new ArrayList<>();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Calendar calendar = Calendar.getInstance();
        // 今天是一周中的第几天
        int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK);
        if (calendar.getFirstDayOfWeek() == Calendar.SUNDAY) {
            calendar.add(Calendar.DAY_OF_MONTH, 1);
        }
        // 计算一周开始的日期
        calendar.add(Calendar.DAY_OF_MONTH, -dayOfWeek);
        for (int i = 1; i <= 7; i++) {
            calendar.add(Calendar.DAY_OF_MONTH, 1);
            weekList.add(simpleDateFormat.format(calendar.getTime()));
        }
        return weekList;
    }

    public List<String> getMonth() {
        List<String> monthList = new ArrayList<>();
        Calendar calendar = Calendar.getInstance(Locale.CHINA);
        int year = calendar.get(Calendar.YEAR); //年份
        int month = calendar.get(Calendar.MONTH) + 1; //月份
        int day = calendar.getActualMaximum(Calendar.DATE);
        for (int i = 1; i <= day; i++) {
            StringBuilder stringBuilder = new StringBuilder().append(year).append("-");
            if (month < 10) {
                stringBuilder.append(0).append(month).append("-");
            } else {
                stringBuilder.append(month).append("-");
            }
            if (i < 10) {
                stringBuilder.append(0).append(i);
            } else {
                stringBuilder.append(i);
            }
            monthList.add(stringBuilder.toString());
        }
        return monthList;
    }

    public Integer getYear() {
        Calendar calendar = Calendar.getInstance();
        // e.g: 2021
        return calendar.get(Calendar.YEAR);
    }

    /**
     * 根据年月获取对应的月份天数
     **/
    private int getDaysByYearMonth(int year, int month) {
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.YEAR, year);
        calendar.set(Calendar.MONTH, month - 1);
        calendar.set(Calendar.DATE, 1);
        calendar.roll(Calendar.DATE, -1);
        return calendar.get(Calendar.DATE);
    }

    /**
     * String => java.util.Date
     *
     * @param str        表示日期的字符串
     * @param dateFormat 传入字符串的日期表示格式(如:"yyyy-MM-dd HH:mm:ss")
     * @return java.util.Date类型日期对象(如果转换失败则返回null)
     */
    public static Date strToDate(String str, String dateFormat) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat(dateFormat);
        Date date = null;
        try {
            date = simpleDateFormat.parse(str);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return date;
    }

    /**
     * Date -> LocalDateTime
     * @param date
     * @return
     */
    public static LocalDateTime dateToLocalDateTime(Date date){
        return date.toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime();
    }

    /***
     * 获取当前时间
     * @return
     */
    public static String  getCurrentDate(){
        return  formatDate(new Date(),null);
    }

    /***
     * 字符串日期格式化
     * @param date
     * @param format
     * @return
     */
    public static String formatDate(String date , String format){
        if(format == null ){
            format = "yyyy-MM-dd";
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

        SimpleDateFormat formatSDF = new SimpleDateFormat(format);
        // 转化成日期类型
        try {
            Date startDate = sdf.parse(date);
            date = formatSDF.format(startDate);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return date;
    }
    public  static  String formatDate(Date dateTime , String format){
        if(format == null ){
            format = "yyyy-MM-dd";
        }
        String date = "";
        SimpleDateFormat formatSDF = new SimpleDateFormat(format);
        // 转化成日期类型
        try {
            date = formatSDF.format(dateTime);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return date;
    }


    /**
     * 格式化
     * @param date
     * @param format
     * @return
     */
    public static String dateformat(String date, String format) {
        SimpleDateFormat sformat = new SimpleDateFormat(format);
        Date _date = null;
        try {
            _date = sformat.parse(date);
        } catch (ParseException var5) {
            var5.printStackTrace();
        }
        return sformat.format(_date);
    }

    /***
     * 两个时间差
     * @param date1
     * @param date2
     * @return
     */
    public static int differenceTime(String  date1,String date2){
        int daysDifference = 1;
        try{
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            // 计算两个日期之间的差值
            daysDifference = org.apache.commons.lang3.time.DateUtils.toCalendar( sdf.parse(date2)).get(Calendar.DAY_OF_YEAR)
                    - org.apache.commons.lang3.time.DateUtils.toCalendar( sdf.parse(date1)).get(Calendar.DAY_OF_YEAR); // 直接计算天数差值
        }catch(Exception e){
            e.printStackTrace();
        }
        return daysDifference;
    }
}