以下是一个简单的 Java 时间工具类,包含了一些基本的时间转换和格式化方法:

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

public class DateUtils {

    private static final String DEFAULT_PATTERN = 'yyyy-MM-dd HH:mm:ss';

    /**
     * 将 Date 对象格式化为指定格式的字符串
     * @param date Date 对象
     * @param pattern 时间格式
     * @return 格式化后的字符串
     */
    public static String format(Date date, String pattern) {
        if (date == null || pattern == null || pattern.isEmpty()) {
            return '';
        }
        SimpleDateFormat sdf = new SimpleDateFormat(pattern);
        return sdf.format(date);
    }

    /**
     * 将字符串解析为 Date 对象
     * @param str 待解析的字符串
     * @param pattern 时间格式
     * @return 解析后的 Date 对象
     * @throws ParseException 解析异常
     */
    public static Date parse(String str, String pattern) throws ParseException {
        if (str == null || pattern == null || pattern.isEmpty()) {
            return null;
        }
        SimpleDateFormat sdf = new SimpleDateFormat(pattern);
        return sdf.parse(str);
    }

    /**
     * 获取指定日期的年份
     * @param date Date 对象
     * @return 年份
     */
    public static int getYear(Date date) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        return cal.get(Calendar.YEAR);
    }

    /**
     * 获取指定日期的月份
     * @param date Date 对象
     * @return 月份
     */
    public static int getMonth(Date date) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        return cal.get(Calendar.MONTH) + 1; // 月份从 0 开始,需要加 1
    }

    /**
     * 获取指定日期的日份
     * @param date Date 对象
     * @return 日份
     */
    public static int getDay(Date date) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        return cal.get(Calendar.DAY_OF_MONTH);
    }

    /**
     * 获取指定日期的小时数
     * @param date Date 对象
     * @return 小时数
     */
    public static int getHour(Date date) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        return cal.get(Calendar.HOUR_OF_DAY);
    }

    /**
     * 获取指定日期的分钟数
     * @param date Date 对象
     * @return 分钟数
     */
    public static int getMinute(Date date) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        return cal.get(Calendar.MINUTE);
    }

    /**
     * 获取指定日期的秒数
     * @param date Date 对象
     * @return 秒数
     */
    public static int getSecond(Date date) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        return cal.get(Calendar.SECOND);
    }

    /**
     * 比较两个日期的大小
     * @param date1 第一个 Date 对象
     * @param date2 第二个 Date 对象
     * @return 如果第一个日期早于第二个日期,返回 -1;如果两个日期相等,返回 0;否则返回 1。
     */
    public static int compare(Date date1, Date date2) {
        if (date1 == null && date2 == null) {
            return 0;
        } else if (date1 == null) {
            return -1;
        } else if (date2 == null) {
            return 1;
        } else {
            return date1.compareTo(date2);
        }
    }

    /**
     * 获取当前时间的 Date 对象
     * @return 当前时间的 Date 对象
     */
    public static Date getCurrentDate() {
        return new Date();
    }

    /**
     * 获取当前时间的指定格式字符串
     * @param pattern 时间格式
     * @return 当前时间的指定格式字符串
     */
    public static String getCurrentDateString(String pattern) {
        return format(getCurrentDate(), pattern);
    }

    /**
     * 获取当前时间的默认格式字符串 ('yyyy-MM-dd HH:mm:ss')
     * @return 当前时间的默认格式字符串
     */
    public static String getCurrentDateString() {
        return getCurrentDateString(DEFAULT_PATTERN);
    }

}

这个工具类包含了以下方法:

  • format(Date date, String pattern):将 Date 对象格式化为指定格式的字符串;
  • parse(String str, String pattern):将字符串解析为 Date 对象;
  • getYear(Date date)getMonth(Date date)getDay(Date date)getHour(Date date)getMinute(Date date)getSecond(Date date):获取指定日期的年、月、日、小时、分钟、秒;
  • compare(Date date1, Date date2):比较两个日期的大小;
  • getCurrentDate():获取当前时间的 Date 对象;
  • getCurrentDateString(String pattern)getCurrentDateString():获取当前时间的指定格式字符串或默认格式字符串。

使用示例:

Date now = DateUtils.getCurrentDate(); // 获取当前时间的 Date 对象
String nowStr = DateUtils.getCurrentDateString(); // 获取当前时间的默认格式字符串
String formatStr = DateUtils.format(now, 'yyyy年MM月dd日'); // 将 Date 对象格式化为指定格式字符串
Date parseDate = DateUtils.parse('2022-01-01 00:00:00', 'yyyy-MM-dd HH:mm:ss'); // 将字符串解析为 Date 对象
int year = DateUtils.getYear(now); // 获取年份
int month = DateUtils.getMonth(now); // 获取月份
int day = DateUtils.getDay(now); // 获取日份
int hour = DateUtils.getHour(now); // 获取小时数
int minute = DateUtils.getMinute(now); // 获取分钟数
int second = DateUtils.getSecond(now); // 获取秒数
int compareResult = DateUtils.compare(now, parseDate); // 比较两个日期的大小

注意:时间格式中的格式化符号需要根据实际需要进行调整。在解析字符串时,如果字符串格式和指定的格式不一致,会抛出 ParseException 异常。在比较两个日期的大小时,如果两个日期中有一个为 null,会根据最终结果进行判断。

Java 时间工具类:日期格式化、解析、获取和比较

原文地址: https://www.cveoy.top/t/topic/lOsk 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录