Please wait...

小波Note

四川 · 成都市多云14 ℃
English

Java common utility classes

成都Thu, December 5, 2024 at 11 PM19.22k152Estimated reading time 38 min
QR code
FavoriteCtrl + D

Time Utility Class

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

/**
 * @author FB
 * @device Windows 11
 * @date 2022/12/1
 * @remarks: [ Time Utility ]
 */
public class TimeUtils {

    /**
     * @remarks: [ Get current timestamp ]
     */
    public static long getTimestamp() {
        return System.currentTimeMillis();
    }

    /**
     * @remarks: [ Get current timestamp ]
     */
    public static long getTimestamp(String format) {
        return Long.parseLong(new SimpleDateFormat(format).format(new Date()));
    }

    /**
     * @remarks: [ Get specified timestamp ]
     */
    public static long getTimestamp(String format, Date time) {
        return Long.parseLong(new SimpleDateFormat(format).format(time));
    }

    /**
     * @remarks: [ Get current time ]
     */
    public static String getTime() {
        return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
    }

    /**
     * @remarks: [ Get current time ]
     */
    public static String getTime(String format) {
        return new SimpleDateFormat(format).format(new Date());
    }

    /**
     * @remarks: [ Get current time ]
     */
    public static String getTime(long timestamp) {
        return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(timestamp));
    }

    /**
     * @remarks: [ Get current time ]
     */
    public static String getTime(long timestamp, String format) {
        return new SimpleDateFormat(format).format(new Date(timestamp));
    }

    /**
     * @remarks: [ Get current time ]
     */
    public static String getTime(Date date) {
        return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(date);
    }

    /**
     * @remarks: [ Get current time ]
     */
    public static String getTime(Date date, String format) {
        return new SimpleDateFormat(format).format(date);
    }

    /**
     * @remarks: [ Get current time ]
     */
    public static String getTime(String timestamp, String format) {
        return new SimpleDateFormat(format).format(new Date(Long.parseLong(timestamp)));
    }

    /**
     * @remarks: [ Get yesterday's time ]
     */
    public static String getYesterday() {
        return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(System.currentTimeMillis() - 86400000));
    }

    /**
     * @remarks: [ Get yesterday's time ]
     */
    public static String getYesterday(String format) {
        return new SimpleDateFormat(format).format(new Date(System.currentTimeMillis() - 86400000));
    }

    /**
     * @remarks: [ Get tomorrow's time ]
     */
    public static String getTomorrow() {
        return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(System.currentTimeMillis() + 86400000));
    }

    /**
     * @remarks: [ Get tomorrow's time ]
     */
    public static String getTomorrow(String format) {
        return new SimpleDateFormat(format).format(new Date(System.currentTimeMillis() + 86400000));
    }

    /**
     * @remarks: [ Get the time of a certain day before the specified time ]
     */
    public static String getBeforeDay(long timestamp, int day) {
        return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(timestamp - day * 86400000L));
    }

    /**
     * @remarks: [ Get the time of a certain day before the specified time ]
     */
    public static String getBeforeDay(long timestamp, int day, String format) {
        return new SimpleDateFormat(format).format(new Date(timestamp - day * 86400000L));
    }

    /**
     * @remarks: [ Get the time of a certain day after the specified time ]
     */
    public static String getAfterDay(long timestamp, int day) {
        return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(timestamp + day * 86400000L));
    }

    /**
     * @remarks: [ Get the time of a certain day after the specified time ]
     */
    public static String getAfterDay(long timestamp, int day, String format) {
        return new SimpleDateFormat(format).format(new Date(timestamp + day * 86400000L));
    }

    /**
     * @remarks: [ Get the time of a certain hour before the specified time ]
     */
    public static String getBeforeHour(long timestamp, int hour) {
        return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(timestamp - hour * 3600000L));
    }

    /**
     * @remarks: [ Get the time of a certain hour before the specified time ]
     */
    public static String getBeforeHour(long timestamp, int hour, String format) {
        return new SimpleDateFormat(format).format(new Date(timestamp - hour * 3600000L));
    }

    /**
     * @remarks: [ Get the time of a certain hour after the specified time ]
     */
    public static String getAfterHour(long timestamp, int hour) {
        return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(timestamp + hour * 3600000L));
    }

    /**
     * @remarks: [ Get the time of a certain hour after the specified time ]
     */
    public static String getAfterHour(long timestamp, int hour, String format) {
        return new SimpleDateFormat(format).format(new Date(timestamp + hour * 3600000L));
    }

    /**
     * @remarks: [ Get the time of a certain minute before the specified time ]
     */
    public static String getBeforeMinute(long timestamp, int minute) {
        return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(timestamp - minute * 60000L));
    }

    /**
     * @remarks: [ Get the time of a certain minute before the specified time ]
     */
    public static String getBeforeMinute(long timestamp, int minute, String format) {
        return new SimpleDateFormat(format).format(new Date(timestamp - minute * 60000L));
    }

    /**
     * @remarks: [ Get the time of a certain minute after the specified time ]
     */
    public static String getAfterMinute(long timestamp, int minute) {
        return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(timestamp + minute * 60000L));
    }

    /**
     * @remarks: [ Get the time of a certain minute after the specified time ]
     */
    public static String getAfterMinute(long timestamp, int minute, String format) {
        return new SimpleDateFormat(format).format(new Date(timestamp + minute * 60000L));
    }

    /**
     * @remarks: [ Get the time of a certain second before the specified time ]
     */
    public static String getBeforeSecond(long timestamp, int second) {
        return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(timestamp - second * 1000L));
    }

    /**
     * @remarks: [ Get the time of a certain second before the specified time ]
     */
    public static String getBeforeSecond(long timestamp, int second, String format) {
        return new SimpleDateFormat(format).format(new Date(timestamp - second * 1000L));
    }

    /**
     * @remarks: [ Get the time of a certain second after the specified time ]
     */
    public static String getAfterSecond(long timestamp, int second) {
        return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(timestamp + second * 1000L));
    }

    /**
     * @remarks: [ Get the time of a certain second after the specified time ]
     */
    public static String getAfterSecond(long timestamp, int second, String format) {
        return new SimpleDateFormat(format).format(new Date(timestamp + second * 1000L));
    }

    /**
     * @remarks: [ Get the time of a certain millisecond before the specified time ]
     */
    public static String getBeforeMillisecond(long timestamp, int millisecond) {
        return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(timestamp - millisecond));
    }

    /**
     * @remarks: [ Get the time of a certain millisecond before the specified time ]
     */
    public static String getBeforeMillisecond(long timestamp, int millisecond, String format) {
        return new SimpleDateFormat(format).format(new Date(timestamp - millisecond));
    }

    /**
     * @remarks: [ Get the time of a certain millisecond after the specified time ]
     */
    public static String getAfterMillisecond(long timestamp, int millisecond) {
        return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(timestamp + millisecond));
    }

    /**
     * @remarks: [ Get the time of a certain millisecond after the specified time ]
     */
    public static String getAfterMillisecond(long timestamp, int millisecond, String format) {
        return new SimpleDateFormat(format).format(new Date(timestamp + millisecond));
    }

    /**
     * @remarks: [ Get the day of the week for the specified time ]
     */
    public static String getWeek(Date date) {
        return new SimpleDateFormat("EEEE").format(date);
    }

    /**
     * @remarks: [ Get the month for the specified time ]
     */
    public static String getMonth(Date date) {
        return new SimpleDateFormat("MMMM").format(date);
    }

    /**
     * @remarks: [ Get the year for the specified time ]
     */
    public static String getYear(Date date) {
        return new SimpleDateFormat("yyyy").format(date);
    }

    /**
     * @remarks: [ Convert string time to date ]
     */
    public static Date getDate(String time) {
        try {
            return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(time);
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * @remarks: [ Get the time difference from the current time to the specified time ]
     */
    public static String getBetweenTime(long timestamp) {
        long between = System.currentTimeMillis() - timestamp;
        if (between < 1000L) {
            return "Just now";
        } else if (between < 60000L) {
            return between / 1000L + " seconds ago";
        } else if (between < 3600000L) {
            return between / 60000L + " minutes ago";
        } else if (between < 86400000L) {
            return between / 3600000L + " hours ago";
        } else if (between < 2592000000L) {
            return between / 86400000L + " days ago";
        } else if (between < 31104000000L) {
            return between / 2592000000L + " months ago";
        } else {
            return between / 31104000000L + " years ago";
        }
    }

    /**
     * @remarks: [ Get the number of seconds from the current time to 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: [ Get all hour collections between two times ]
     */
    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;
    }

}

    
Collapse

Regex Utility

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

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

    /**
     * @remarks: [ Validate email ]
     */
    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: [ Validate ID card ]
     */
    public static boolean isIdCard(String idCard) {
        String regex = "(^\\d{15}$)|(^\\d{18}$)|(^\\d{17}(\\d|X|x)$)";
        return idCard.matches(regex);
    }

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

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

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

    /**
     * @remarks: [ Validate IP address ]
     */
    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: [ Validate domain ]
     */
    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: [ Validate JSON ]
     */
    public static boolean isJson(String json) {
        String regex = "^(\\{.*\\})|(\\[.*\\])$";
        return json.matches(regex);
    }

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

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

    /**
     * @remarks: [ Validate datetime ]
     */
    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: [ Validate hexadecimal ]
     */
    public static boolean isHex(String hex) {
        String regex = "^[A-Fa-f0-9]+$";
        return hex.matches(regex);
    }

    /**
     * @remarks: [ Validate contains numbers and letters ]
     */
    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: [ Validate contains curly braces ]
     */
    public static boolean isBrackets(String brackets) {
        String regex = ".*\\{.*\\}.*";
        return brackets.matches(regex);
    }

}

    
Collapse

Redis Utility

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);
  }
}

    
Collapse
Astral