请稍等...

小波Note

四川 · 成都市11 ℃
中文

Java 常用的工具类

成都2024年12月5日周四 23时17.57k151预计阅读时间 35 分钟
二维码
收藏Ctrl + D

时间工具类

TimeUtils.java
        import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * @author FB by Linux
 * @device Windows 11
 * @date 2022/12/1
 * @remarks: [ 时间工具 ]
 */
public class TimeUtils {

    /**
     * @remarks: [ 获取当前时间戳 ]
     */
    public static long getTimestamp() {
        return System.currentTimeMillis();
    }

    /**
     * @remarks: [ 获取当前时间戳 ]
     */
    public static long getTimestamp(String format) {
        return Long.parseLong(new SimpleDateFormat(format).format(new Date()));
    }

    /**
     * @remarks: [ 获取指定时间戳 ]
     */
    public static long getTimestamp(String format, Date time) {
        return Long.parseLong(new SimpleDateFormat(format).format(time));
    }

    /**
     * @remarks: [ 获取当前时间 ]
     */
    public static String getTime() {
        return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
    }

    /**
     * @remarks: [ 获取当前时间 ]
     */
    public static String getTime(String format) {
        return new SimpleDateFormat(format).format(new Date());
    }

    /**
     * @remarks: [ 获取当前时间 ]
     */
    public static String getTime(long timestamp) {
        return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(timestamp));
    }

    /**
     * @remarks: [ 获取当前时间 ]
     */
    public static String getTime(long timestamp, String format) {
        return new SimpleDateFormat(format).format(new Date(timestamp));
    }

    /**
     * @remarks: [ 获取当前时间 ]
     */
    public static String getTime(Date date) {
        return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(date);
    }

    /**
     * @remarks: [ 获取当前时间 ]
     */
    public static String getTime(Date date, String format) {
        return new SimpleDateFormat(format).format(date);
    }

    /**
     * @remarks: [ 获取当前时间 ]
     */
    public static String getTime(String timestamp, String format) {
        return new SimpleDateFormat(format).format(new Date(Long.parseLong(timestamp)));
    }

    /**
     * @remarks: [ 获取昨天时间 ]
     */
    public static String getYesterday() {
        return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(System.currentTimeMillis() - 86400000));
    }

    /**
     * @remarks: [ 获取昨天时间 ]
     */
    public static String getYesterday(String format) {
        return new SimpleDateFormat(format).format(new Date(System.currentTimeMillis() - 86400000));
    }

    /**
     * @remarks: [ 获取明天时间 ]
     */
    public static String getTomorrow() {
        return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(System.currentTimeMillis() + 86400000));
    }

    /**
     * @remarks: [ 获取明天时间 ]
     */
    public static String getTomorrow(String format) {
        return new SimpleDateFormat(format).format(new Date(System.currentTimeMillis() + 86400000));
    }

    /**
     * @remarks: [ 获取指定时间前某天 ]
     */
    public static String getBeforeDay(long timestamp, int day) {
        return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(timestamp - day * 86400000L));
    }

    /**
     * @remarks: [ 获取指定时间前某天 ]
     */
    public static String getBeforeDay(long timestamp, int day, String format) {
        return new SimpleDateFormat(format).format(new Date(timestamp - day * 86400000L));
    }

    /**
     * @remarks: [ 获取指定时间后某天 ]
     */
    public static String getAfterDay(long timestamp, int day) {
        return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(timestamp + day * 86400000L));
    }

    /**
     * @remarks: [ 获取指定时间后某天 ]
     */
    public static String getAfterDay(long timestamp, int day, String format) {
        return new SimpleDateFormat(format).format(new Date(timestamp + day * 86400000L));
    }

    /**
     * @remarks: [ 获取指定时间前某小时 ]
     */
    public static String getBeforeHour(long timestamp, int hour) {
        return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(timestamp - hour * 3600000L));
    }

    /**
     * @remarks: [ 获取指定时间前某小时 ]
     */
    public static String getBeforeHour(long timestamp, int hour, String format) {
        return new SimpleDateFormat(format).format(new Date(timestamp - hour * 3600000L));
    }

    /**
     * @remarks: [ 获取指定时间后某小时 ]
     */
    public static String getAfterHour(long timestamp, int hour) {
        return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(timestamp + hour * 3600000L));
    }

    /**
     * @remarks: [ 获取指定时间后某小时 ]
     */
    public static String getAfterHour(long timestamp, int hour, String format) {
        return new SimpleDateFormat(format).format(new Date(timestamp + hour * 3600000L));
    }

    /**
     * @remarks: [ 获取指定时间前某分钟 ]
     */
    public static String getBeforeMinute(long timestamp, int minute) {
        return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(timestamp - minute * 60000L));
    }

    /**
     * @remarks: [ 获取指定时间前某分钟 ]
     */
    public static String getBeforeMinute(long timestamp, int minute, String format) {
        return new SimpleDateFormat(format).format(new Date(timestamp - minute * 60000L));
    }

    /**
     * @remarks: [ 获取指定时间后某分钟 ]
     */
    public static String getAfterMinute(long timestamp, int minute) {
        return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(timestamp + minute * 60000L));
    }

    /**
     * @remarks: [ 获取指定时间后某分钟 ]
     */
    public static String getAfterMinute(long timestamp, int minute, String format) {
        return new SimpleDateFormat(format).format(new Date(timestamp + minute * 60000L));
    }

    /**
     * @remarks: [ 获取指定时间前某秒 ]
     */
    public static String getBeforeSecond(long timestamp, int second) {
        return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(timestamp - second * 1000L));
    }

    /**
     * @remarks: [ 获取指定时间前某秒 ]
     */
    public static String getBeforeSecond(long timestamp, int second, String format) {
        return new SimpleDateFormat(format).format(new Date(timestamp - second * 1000L));
    }

    /**
     * @remarks: [ 获取指定时间后某秒 ]
     */
    public static String getAfterSecond(long timestamp, int second) {
        return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(timestamp + second * 1000L));
    }

    /**
     * @remarks: [ 获取指定时间后某秒 ]
     */
    public static String getAfterSecond(long timestamp, int second, String format) {
        return new SimpleDateFormat(format).format(new Date(timestamp + second * 1000L));
    }

    /**
     * @remarks: [ 获取指定时间前某毫秒 ]
     */
    public static String getBeforeMillisecond(long timestamp, int millisecond) {
        return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(timestamp - millisecond));
    }

    /**
     * @remarks: [ 获取指定时间前某毫秒 ]
     */
    public static String getBeforeMillisecond(long timestamp, int millisecond, String format) {
        return new SimpleDateFormat(format).format(new Date(timestamp - millisecond));
    }

    /**
     * @remarks: [ 获取指定时间后某毫秒 ]
     */
    public static String getAfterMillisecond(long timestamp, int millisecond) {
        return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(timestamp + millisecond));
    }

    /**
     * @remarks: [ 获取指定时间后某毫秒 ]
     */
    public static String getAfterMillisecond(long timestamp, int millisecond, String format) {
        return new SimpleDateFormat(format).format(new Date(timestamp + millisecond));
    }

    /**
     * @remarks: [ 获取指定时间星期几 ]
     */
    public static String getWeek(Date date) {
        return new SimpleDateFormat("EEEE").format(date);
    }

    /**
     * @remarks: [ 获取指定时间月份 ]
     */
    public static String getMonth(Date date) {
        return new SimpleDateFormat("MMMM").format(date);
    }

    /**
     * @remarks: [ 获取指定时间年 ]
     */
    public static String getYear(Date date) {
        return new SimpleDateFormat("yyyy").format(date);
    }

    /**
     * @remarks: [ 字符串时间转日期 ]
     */
    public static Date getDate(String time) {
        try {
            return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(time);
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * @remarks: [ 获取当前时间到指定时间的时间差 ]
     */
    public static String getBetweenTime(long timestamp) {
        long between = System.currentTimeMillis() - timestamp;
        if (between < 1000L) {
            return "刚刚";
        } else if (between < 60000L) {
            return between / 1000L + "秒前";
        } else if (between < 3600000L) {
            return between / 60000L + "分钟前";
        } else if (between < 86400000L) {
            return between / 3600000L + "小时前";
        } else if (between < 2592000000L) {
            return between / 86400000L + "天前";
        } else if (between < 31104000000L) {
            return between / 2592000000L + "月前";
        } else {
            return between / 31104000000L + "年前";
        }
    }

    /**
     * @remarks: [ 获取当前时间到 23:59:59 的秒数 ]
     */
    public static long getSecondsToLast() {
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.HOUR_OF_DAY, 23);
        calendar.set(Calendar.MINUTE, 59);
        calendar.set(Calendar.SECOND, 59);
        return (calendar.getTimeInMillis() - System.currentTimeMillis()) / 1000;
    }

    /**
     * @remarks: [ 获取两个时间之间所有小时集合 ]
     */
    public static List<String> getHoursBetweenTime(long start, long end) {
        int size = (int) ((end - start) / 3600000L);
        List<String> hours = new ArrayList<>(size);
        for (int i = 1; i <= size; i++) {
            hours.add(getAfterHour(start, i));
        }
        return hours;
    }

}

    
收起

正则工具

RegexUtils.java
        /**
 * @author FB by Linux
 * @device Windows 11
 * @date 2022/12/1
 * @remarks: [ 正则工具 ]
 */
public class RegexUtils {

    /**
     * @remarks: [ 验证手机号 ]
     */
    public static boolean isPhone(String phone) {
        String regex = "^1[3-9]\\d{9}$";
        return phone.matches(regex);
    }

    /**
     * @remarks: [ 验证邮箱 ]
     */
    public static boolean isEmail(String email) {
        String regex = "^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\\.[a-zA-Z0-9_-]+)+$";
        return email.matches(regex);
    }

    /**
     * @remarks: [ 验证身份证 ]
     */
    public static boolean isIdCard(String idCard) {
        String regex = "(^\\d{15}$)|(^\\d{18}$)|(^\\d{17}(\\d|X|x)$)";
        return idCard.matches(regex);
    }

    /**
     * @remarks: [ 验证数字 ]
     */
    public static boolean isNumber(String number) {
        String regex = "^[0-9]*$";
        return number.matches(regex);
    }

    /**
     * @remarks: [ 验证中文 ]
     */
    public static boolean isChinese(String chinese) {
        String regex = "^[\u4e00-\u9fa5]{0,}$";
        return chinese.matches(regex);
    }

    /**
     * @remarks: [ 验证Url ]
     */
    public static boolean isUrl(String url) {
        String regex = "http(s)?://([\\w-]+\\.)+[\\w-]+(/[\\w- ./?%&=]*)?";
        return url.matches(regex);
    }

    /**
     * @remarks: [ 验证IP ]
     */
    public static boolean isIp(String ip) {
        String regex = "((25[0-5]|2[0-4]\\d|((1\\d{2})|([1-9]?\\d)))\\.){3}(25[0-5]|2[0-4]\\d|((1\\d{2})|([1-9]?\\d)))";
        return ip.matches(regex);
    }

    /**
     * @remarks: [ 验证域名 ]
     */
    public static boolean isDomain(String domain) {
        String regex = "^[a-zA-Z0-9]+([a-zA-Z0-9\\-]{0,61}[a-zA-Z0-9])?(\\.[a-zA-Z0-9]+([a-zA-Z0-9\\-]{0,61}[a-zA-Z0-9])?)*$";
        return domain.matches(regex);
    }

    /**
     * @remarks: [ 验证JSON ]
     */
    public static boolean isJson(String json) {
        String regex = "^(\\{.*\\})|(\\[.*\\])$";
        return json.matches(regex);
    }

    /**
     * @remarks: [ 验证日期 ]
     */
    public static boolean isDate(String date) {
        String regex = "^\\d{4}-\\d{2}-\\d{2}$";
        return date.matches(regex);
    }

    /**
     * @remarks: [ 验证时间 ]
     */
    public static boolean isTime(String time) {
        String regex = "^([01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d$";
        return time.matches(regex);
    }

    /**
     * @remarks: [ 验证日期时间 ]
     */
    public static boolean isDateTime(String dateTime) {
        String regex = "^\\d{4}-\\d{2}-\\d{2} ([01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d$";
        return dateTime.matches(regex);
    }

    /**
     * @remarks: [ 验证十六进制 ]
     */
    public static boolean isHex(String hex) {
        String regex = "^[A-Fa-f0-9]+$";
        return hex.matches(regex);
    }

    /**
     * @remarks: [ 验证包含数字和字母 ]
     */
    public static boolean isNumberAndLetter(String numberAndLetter, int min, int max) {
        String regex = "^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{" + min + "," + max +"}$";
        return numberAndLetter.matches(regex);
    }

    /**
     * @remarks: [ 验证是否包含大括号 ]
     */
    public static boolean isBrackets(String brackets) {
        String regex = ".*\\{.*\\}.*";
        return brackets.matches(regex);
    }

}

    
收起

Redis工具

RedisUtil.java
        import org.springframework.data.redis.connection.DataType;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * @author FB by Linux
 * @device Windows 11
 * @date 2022/12/1
 * @remarks: [ Redis工具 ]
 */
@Component
public class RedisUtil {
  private final RedisTemplate<String, String> redisTemplate;

  public RedisUtil(RedisTemplate<String, String> redisTemplate) {
    this.redisTemplate = redisTemplate;
  }

  public Set<String> getKeys(String key) {
    return this.redisTemplate.keys(key);
  }
  
  public boolean isExist(String key) {
    return Boolean.TRUE.equals(this.redisTemplate.hasKey(key));
  }
  
  public boolean setExpireTime(String key, long time, TimeUnit unit) {
    return Boolean.TRUE.equals(this.redisTemplate.expire(key, time, unit));
  }
  
  public boolean setExpireTime(String key, Date date) {
    return Boolean.TRUE.equals(this.redisTemplate.expireAt(key, date));
  }
  
  public Long getExpireTime(String key, TimeUnit unit) {
    return this.redisTemplate.getExpire(key, unit);
  }
  
  public Long getExpireTime(String key) {
    return this.redisTemplate.getExpire(key);
  }
  
  public boolean persist(String key) {
    return Boolean.TRUE.equals(this.redisTemplate.persist(key));
  }
  
  public String randomKey() {
    return this.redisTemplate.randomKey();
  }
  
  public boolean moveKey(String key, int dIndex) {
    return Boolean.TRUE.equals(this.redisTemplate.move(key, dIndex));
  }
  
  public boolean rename(String oldKey, String newKey) {
    return Boolean.TRUE.equals(this.redisTemplate.renameIfAbsent(oldKey, newKey));
  }
  
  public DataType keyType(String key) {
    return this.redisTemplate.type(key);
  }
  
  public void delete(String... keys) {
    for (String key : keys)
      this.redisTemplate.delete(key); 
  }
  
  public void set(String key, String value) {
    this.redisTemplate.opsForValue().set(key, value);
  }
  
  public void set(String key, String value, long time, TimeUnit unit) {
    this.redisTemplate.opsForValue().set(key, value, time, unit);
  }
  
  public void multiSet(Map<String, String> maps) {
    this.redisTemplate.opsForValue().multiSet(maps);
  }
  
  public boolean setIfAbsent(String key, String value) {
    return Boolean.TRUE.equals(this.redisTemplate.opsForValue().setIfAbsent(key, value));
  }
  
  public boolean multiSetIfAbsent(Map<String, String> maps) {
    return Boolean.TRUE.equals(this.redisTemplate.opsForValue().multiSetIfAbsent(maps));
  }
  
  public Integer append(String key, String value) {
    return this.redisTemplate.opsForValue().append(key, value);
  }
  
  public Object get(String key) {
    return this.redisTemplate.opsForValue().get(key);
  }
  
  public List<String> multiGet(Collection<String> keys) {
    return this.redisTemplate.opsForValue().multiGet(keys);
  }
  
  public Long getSize(String key) {
    return this.redisTemplate.opsForValue().size(key);
  }
  
  public void incrByLong(String key, long incr) {
    this.redisTemplate.opsForValue().increment(key, incr);
  }
  
  public Double incrByLong(String key, Double incr) {
    return this.redisTemplate.opsForValue().increment(key, incr);
  }

  /**
   * ZSet
   * ==============================================================================
   */

  public Set<String> reverseRange(String key, long start, long end) {
    return this.redisTemplate.opsForZSet().reverseRange(key, start, end);
  }

  public Double getScore(String key, String value) {
    return this.redisTemplate.opsForZSet().score(key, value);
  }

  public void addZSet(String key, String value, double score) {
    this.redisTemplate.opsForZSet().add(key, value, score);
  }

  public void incrementScore(String key, String value, double score) {
    this.redisTemplate.opsForZSet().incrementScore(key, value, score);
  }
}

    
收起
星空