Android时间工具类

奋斗吧
奋斗吧
擅长邻域:未填写

标签: Android时间工具类 Android博客 51CTO博客

2023-07-24 18:24:47 74浏览

Android时间工具类,时间在软件开发中是一个常见的处理需求,包括获取当前时间、时间格式化、时间比较、时间差计算等操作。为了简化开发过程,可以编写一个时间工具类来封装这些常用的时间操作方法。

✍️作者简介:沫小北(专注于Android、Web、TCP/IP等技术方向)

🐳博客主页:沫小北 开源中国稀土掘金51cto博客博客园知乎简书慕课网CSDN

🌐系列专栏:码农小北 🔔如果文章对您有一定的帮助请👉关注✨、点赞👍、收藏📂、评论💬。

🔥如需转载请参考【转载须知】

时间在软件开发中是一个常见的处理需求,包括获取当前时间、时间格式化、时间比较、时间差计算等操作。为了简化开发过程,可以编写一个时间工具类来封装这些常用的时间操作方法。

因工具类时间类主要分格式化和时间计算所以做一个拆分

DateUtil.java 主要功能格式化时间工具类

TimeUtil.java 时间工具处理类

DateUtil 时间工具类

功能介绍

时间工具类封装了以下常用功能:

  • 获取当前时间:获取系统当前的日期和时间。
  • 格式化时间:将日期对象或时间戳格式化为指定的时间格式。
  • 解析时间:将字符串时间解析为日期对象。
  • 获取时间差:计算两个日期之间的时间差,包括天数、小时数、分钟数等。
  • 判断时间区间:判断指定时间是否在给定的时间区间内。
  • 判断闰年:判断指定年份是否为闰年。
  • 获取年份、月份、星期等:从日期对象中提取年份、月份、星期等信息。

主要方法和功能:

  • getCurrentDate(String pattern):获取当前时间的字符串表示。
  • formatToStr(long timestamp, String pattern):将时间戳格式化为指定格式的字符串。
  • formatToStr(Date date, String pattern):将日期对象格式化为指定格式的字符串。
  • formatStringDate(String dateString, String format):将字符串时间按照指定格式进行格式化。
  • getCurrentTime():获取当前时间的日期对象。
  • formatTime(Date date, String pattern):将日期对象格式化为指定格式的时间字符串。
  • parseTime(String time, String pattern):解析指定格式的时间字符串为日期对象。
  • getTimeDifference(Date date1, Date date2, TimeUnit timeUnit):计算两个日期之间的时间差。
  • isInTimeRange(Date time, Date startTime, Date endTime):判断指定时间是否在给定时间区间内。
  • isLeapYear(int year):判断指定年份是否为闰年。
  • getYearFromDate(Date date):获取指定日期对象的年份。
  • getMonthFromDate(Date date):获取指定日期对象的月份。
  • getWeekdayFromDate(Date date):获取指定日期对象的星期。

使用示例

下面是的一些常见用法示例:

// 获取当前时间
Date currentTime = DateUtil.getCurrentTime();

// 格式化时间
String formattedTime = DateUtil.formatTime(currentTime, DateUtil.FORMAT_YYYY_MM_DD_HH_MM_SS);

// 解析时间
String timeString = "2023-07-14 12:00:00";
Date parsedTime = DateUtil.parseTime(timeString, DateUtil.FORMAT_YYYY_MM_DD_HH_MM_SS);

// 获取时间差
Date startTime = new Date();
Date endTime = new Date(System.currentTimeMillis() + TimeUnit.HOURS.toMillis(2));
long timeDifference = DateUtil.getTimeDifference(startTime, endTime, TimeUnit.MINUTES);

// 判断时间区间
Date time = new Date();
Date startTime = new Date(System.currentTimeMillis() - TimeUnit.DAYS.toMillis(1));
Date endTime = new Date(System.currentTimeMillis() + TimeUnit.DAYS.toMillis(1));
boolean isInTimeRange = DateUtil.isInTimeRange(time, startTime, endTime);

// 判断闰年
int year = 2023;
boolean isLeapYear = DateUtil.isLeapYear(year);

// 获取年份、月份、星期
int yearFromDate = DateUtil.getYearFromDate(currentTime);
int monthFromDate = DateUtil.getMonthFromDate(currentTime);
int weekdayFromDate = DateUtil.getWeekdayFromDate(currentTime);

示例代码

以下是一个简单的时间工具类的示例代码:

import androidx.core.net.ParseException;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;
import java.util.concurrent.TimeUnit;

/**
 * @author: xtxiaolu
 * @date: 2023/7/14
 * 描述: 主要功能格式化时间工具类
 */
public class DateUtil {

    // 日期格式年份,例如:2022,2023
    public static final String FORMAT_YYYY = "yyyy";
    // 其他格式常量...

    private static final TimeZone DEFAULT_TIMEZONE = TimeZone.getDefault();
    private static TimeZone DefaultTimeZone = TimeZone.getDefault();

    /**
     * 获取当前时间的字符串表示
     *
     * @param pattern 时间格式
     * @return 当前时间的字符串表示
     */
    public static String getCurrentDate(String pattern) {
        return formatToStr(new Date(), pattern);
    }

    /**
     * 将时间戳格式化为指定格式的字符串
     *
     * @param timestamp 时间戳
     * @param pattern   时间格式
     * @return 格式化后的时间字符串
     */
    public static String formatToStr(long timestamp, String pattern) {
        return formatToStr(new Date(timestamp), pattern);
    }

    /**
     * 将日期对象格式化为指定格式的字符串
     *
     * @param date    日期对象
     * @param pattern 时间格式
     * @return 格式化后的时间字符串
     */
    public static String formatToStr(Date date, String pattern) {
        DateFormat dateFormat = getDateFormat(pattern);
        return dateFormat.format(date);
    }

    /**
     * 获取指定格式的日期格式化对象
     *
     * @param pattern 时间格式
     * @return 日期格式化对象
     */
    private static DateFormat getDateFormat(String pattern) {
        SimpleDateFormat dateFormat = new SimpleDateFormat(pattern);
        dateFormat.setTimeZone(DEFAULT_TIMEZONE);
        return dateFormat;
    }

    /**
     * 格式化字符串时间为指定格式
     *
     * @param dateString 字符串时间
     * @param format     格式
     * @return 格式化后的时间字符串
     */
    public static String formatStringDate(String dateString, String format) {
        SimpleDateFormat inputFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        SimpleDateFormat outputFormat = new SimpleDateFormat(format);
        try {
            Date date = inputFormat.parse(dateString);
            return outputFormat.format(date);
        } catch (ParseException | java.text.ParseException e) {
            e.printStackTrace();
        }
        return "";
    }

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

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

    /**
     * 解析指定格式的时间字符串为日期对象
     *
     * @param time    时间字符串
     * @param pattern 时间格式
     * @return 解析后的日期对象
     * @throws ParseException 解析异常
     */
    public static Date parseTime(String time, String pattern) throws ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat(pattern);
        try {
            return sdf.parse(time);
        } catch (java.text.ParseException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 计算两个日期之间的时间差,返回指定时间单位的差值
     *
     * @param date1     第一个日期对象
     * @param date2     第二个日期对象
     * @param timeUnit  时间单位
     * @return 时间差的差值
     */
    public static long getTimeDifference(Date date1, Date date2, TimeUnit timeUnit) {
        long difference = date2.getTime() - date1.getTime();
        return timeUnit.convert(difference, TimeUnit.MILLISECONDS);
    }

    /**
     * 判断指定时间是否在给定时间区间内
     *
     * @param time      待判断的时间
     * @param startTime 时间区间的开始时间
     * @param endTime   时间区间的结束时间
     * @return 如果指定时间在时间区间内,返回 true;否则返回 false
     */
    public static boolean isInTimeRange(Date time, Date startTime, Date endTime) {
        return time.after(startTime) && time.before(endTime);
    }

    /**
     * 判断指定年份是否为闰年
     *
     * @param year 年份
     * @return 如果是闰年,返回 true;否则返回 false
     */
    public static boolean isLeapYear(int year) {
        return (year % 4 == 0 && year % 100 != 0) || year % 400 == 0;
    }

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

    /**
     * 获取指定日期对象的月份
     *
     * @param date 日期对象
     * @return 月份
     */
    public static int getMonthFromDate(Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        return calendar.get(Calendar.MONTH) + 1;
    }

    /**
     * 获取指定日期对象的星期
     *
     * @param date 日期对象
     * @return 星期,1 表示星期一,2 表示星期二,依次类推
     */
    public static int getWeekdayFromDate(Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        return calendar.get(Calendar.DAY_OF_WEEK);
    }
}

TimeUtil 时间工具类

时间工具类提供了一系列用于处理时间的方法,包括获取当前时间、格式化时间、判断时间区间、计算时间差等功能。该工具类基于最新的Android API,并提供了更加简洁和易用的方法。

方法列表

  • getCurrentWeekOfMonth(): 获取当前时间为本月的第几周。
  • getCurrentDayOfWeek(): 获取当前时间为本周的第几天。
  • getCurrentDayOfWeekText(): 返回当前日期是星期几的文本表示。
  • isTimeInRange(time, startTime, endTime): 判断指定时间是否在给定的时间区间内。
  • isTimeInRange(time, startTime, endTime): 判断指定时间是否在给定的时间区间内。
  • isInTimeRange(currentTime, startTime, endTime): 判断指定时间是否在给定的时间区间内。
  • calculateDaysDifference(startDate, endDate): 计算两个日期之间相差的天数。
  • calculateTimeDifference(date): 返回友好的时间跨度表示。

使用示例

// 获取当前时间为本月的第几周
int weekOfMonth = TimeUtil.getCurrentWeekOfMonth();

// 获取当前时间为本周的第几天
int dayOfWeek = TimeUtil.getCurrentDayOfWeek();

// 返回当前日期是星期几的文本表示
String dayOfWeekText = TimeUtil.getCurrentDayOfWeekText();

// 判断指定时间是否在时间区间内
boolean isInRange = TimeUtil.isTimeInRange(time, startTime, endTime);

// 计算两个日期之间相差的天数
long daysDifference = TimeUtil.calculateDaysDifference(startDate, endDate);

// 返回友好的时间跨度表示
String timeDifference = TimeUtil.calculateTimeDifference(date);

示例代码

import java.text.DateFormatSymbols;
import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import java.util.concurrent.TimeUnit;

/**
 * @author: xtxiaolu
 * @date: 2023/7/14
 * 描述:时间工具处理类
 */
public class TimeUtil {

    /**
     * 获取当前时间为本月的第几周
     *
     * @return 本月的第几周
     */
    public static int getCurrentWeekOfMonth() {
        Calendar calendar = Calendar.getInstance();
        int weekOfMonth = calendar.get(Calendar.WEEK_OF_MONTH);
        return weekOfMonth;
    }

    /**
     * 获取当前时间为本周的第几天
     *
     * @return 本周的第几天(1代表周一,7代表周日)
     */
    public static int getCurrentDayOfWeek() {
        LocalDate currentDate = LocalDate.now();
        DayOfWeek dayOfWeek = currentDate.getDayOfWeek();
        int dayOfWeekValue = dayOfWeek.getValue();
        return dayOfWeekValue;
    }

    /**
     * 返回当前日期是星期几
     *
     * @return 例如:星期日、星期一、星期六等等。
     */
    public static String getCurrentDayOfWeekText() {
        Calendar calendar = Calendar.getInstance();
        int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK);
        // 获取星期几文本
        DateFormatSymbols symbols = new DateFormatSymbols(Locale.getDefault());
        String[] dayOfWeekTexts = symbols.getWeekdays();
        if (dayOfWeek >= Calendar.SUNDAY && dayOfWeek <= Calendar.SATURDAY) {
            return dayOfWeekTexts[dayOfWeek];
        } else {
            return "";
        }
    }

    /**
     * 判断指定时间是否在时间区间内
     *
     * @param time        待判断的时间
     * @param startTime   时间区间的开始时间
     * @param endTime     时间区间的结束时间
     * @return 如果指定时间在时间区间内,返回 true;否则返回 false
     */
    public static boolean isTimeInRange(Calendar time, Calendar startTime, Calendar endTime) {
        return time.compareTo(startTime) >= 0 && time.compareTo(endTime) <= 0;
    }

    /**
     * 判断指定时间是否在时间区间内
     *
     * @param time        待判断的时间
     * @param startTime   时间区间的开始时间
     * @param endTime     时间区间的结束时间
     * @return 如果指定时间在时间区间内,返回 true;否则返回 false
     */
    public static boolean isTimeInRange(LocalDateTime time, LocalDateTime startTime, LocalDateTime endTime) {
        return time.compareTo(startTime) >= 0 && time.compareTo(endTime) <= 0;
    }

    /**
     * 判断指定时间是否在时间区间内
     *
     * @param currentTime 待判断的时间
     * @param startTime   时间区间的开始时间
     * @param endTime     时间区间的结束时间
     * @return 如果指定时间在时间区间内,返回 true;否则返回 false
     */
    public static boolean isInTimeRange(Date currentTime, Date startTime, Date endTime) {
        long currentTimeMillis = currentTime.getTime();
        return currentTimeMillis >= startTime.getTime() && currentTimeMillis <= endTime.getTime();
    }

    /**
     * 求两个日期相差天数
     * @param startDate 开始时间
     * @param endDate   结束时间
     * @return 相差天数
     */
    public static long calculateDaysDifference(Date startDate, Date endDate) {
        long differenceMillis = endDate.getTime() - startDate.getTime();
        long differenceDays = TimeUnit.MILLISECONDS.toDays(differenceMillis);
        return differenceDays;
    }


    /**
     * 返回友好时间跨度
     *
     * @param date 需要格式化的时间
     *
     * @return the fit time span
     *         return 小于1分钟,返回"刚刚"
     *         return 小于1小时但大于0分钟,返回"X分钟前"
     *         return 小于1天但大于0小时,返回"X小时前"
     *         return 昨天,返回"昨天"
     *         return 大于1天,返回"X天前"
     */
    public static String calculateTimeDifference(Date date) {
        long currentTime = System.currentTimeMillis();
        long timeDifference = currentTime - date.getTime();
        // 计算时间差对应的单位
        long seconds = timeDifference / 1000;
        long minutes = seconds / 60;
        long hours = minutes / 60;
        long days = hours / 24;

        if (days > 1) {
            // 大于1天,返回"X天前"
            return days + "天前";
        } else if (days == 1) {
            // 昨天,返回"昨天"
            return "昨天";
        } else if (hours > 0) {
            // 小于1天但大于0小时,返回"X小时前"
            return hours + "小时前";
        } else if (minutes > 0) {
            // 小于1小时但大于0分钟,返回"X分钟前"
            return minutes + "分钟前";
        } else {
            // 小于1分钟,返回"刚刚"
            return "刚刚";
        }
    }
}

以上代码全部提供不在提供代码仓库链接 如有疑问请留言

如果以上的时间工具类对您有所帮助,请不吝点赞和收藏。这个工具类旨在简化时间处理的操作,提供了一系列方便易用的方法,帮助您更高效地处理时间相关的业务逻辑。无论是获取当前时间的某个特定值,还是计算时间差、判断时间区间,亦或是格式化时间,该工具类都能满足您的需求。使用这个工具类,您可以更轻松地处理时间操作,提高开发效率。如果您觉得这个工具类有用,请给予您的支持,以便将它收藏起来方便日后使用。感谢您的支持和喜爱!

好博客就要一起分享哦!分享海报

此处可发布评论

评论(0展开评论

暂无评论,快来写一下吧

展开评论

您可能感兴趣的博客

客服QQ 1913284695