Android时间工具类

✍️作者简介:小北编程(专注于HarmonyOS、Android、Java、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 "刚刚";
        }
    }
}

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

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

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
### 回答1: Android BLE(蓝牙低功耗)工具类是用于简化在Android应用中与蓝牙设备进行通信的开发过程的类。该工具类提供了一系列方法和功能,使得与BLE设备的连接、数据传输和操作变得更加简单和高效。 首先,该工具类提供了与BLE设备进行连接和断开连接的方法。通过调用连接方法,我们可以与目标BLE设备建立起稳定的连接,并获取一个用于后续通信的Gatt服务。同时,断开连接方法可以安全地中断与设备之间的通信,释放资源并确保连接关闭。 其次,该工具类还包含了搜索BLE设备的功能。我们可以使用这个功能来扫描附近的BLE设备,并获取它们的名称、MAC地址和其他相关信息。这可以帮助我们快速找到需要连接的设备,并进行下一步操作。 在连接建立后,该工具类还提供了读取、写入和监听BLE设备特征的方法。我们可以通过读取特征值来获取设备传输的数据,通过写入特征值来向设备发送指令,或者通过监听特征值的变化来实时获取设备的状态更新。这些方法使得与BLE设备的数据交互变得非常方便。 此外,该工具类还支持BLE设备的服务发现、特征值读写的状态回调以及连接状态的监听等功能。它提供了丰富的回调接口,使得我们可以根据需求进行相应的处理和操作。 总之,Android BLE工具类为开发人员提供了一系列简化蓝牙低功耗通信过程的方法和功能。它的使用可以大大减少开发工作的复杂性和难度,提高开发效率,并帮助我们更好地实现与BLE设备的交互。 ### 回答2: Android BLE工具类是一种用于简化与BLE(蓝牙低功耗)设备通信的工具类。它提供了一系列便捷的方法和功能,使开发者能够更容易地实现BLE设备的连接、搜索、数据传输等操作。 首先,Android BLE工具类可以帮助开发者建立与BLE设备的连接。它封装了与设备的GATT(通用属性)连接过程,使连接操作更加简单和高效。通过调用相应的方法,开发者可以轻松地与设备进行连接,并可以处理连接成功或失败的回调。 其次,该工具类还提供了BLE设备搜索的功能。开发者可以使用相应的方法启动BLE设备搜索,并可以设置搜索的时间和过滤条件。搜索结果将以回调方式返回,开发者可以根据搜索结果选择要连接的设备。 此外,该工具类还封装了BLE设备的通信接口,使开发者能够方便地发送和接收数据。开发者可以使用相应的方法向设备发送命令或请求,并可以处理设备返回的数据。这些方法包括读取特征值、写入特征值、设置通知等。 最后,该工具类还提供了其他一些便捷的功能,如断开设备连接、设置连接超时、监测设备状态等。开发者可以根据自己的需求选择使用这些功能来提高开发效率和用户体验。 总之,Android BLE工具类是一种能够简化与BLE设备通信的工具,它提供了连接设备、搜索设备、数据传输等一系列功能,帮助开发者更方便地实现BLE设备的相关操作。 ### 回答3: Android BLE(Bluetooth Low Energy)工具类是一种在Android平台上使用的工具类,用于简化与蓝牙低功耗设备通信的操作。 Android BLE工具类的主要功能包括以下几个方面: 1. 初始化:Android BLE工具类提供初始化蓝牙适配器的功能,以及检查设备是否支持BLE功能。 2. 扫描设备:Android BLE工具类提供开始和停止扫描BLE设备的方法,并且可以根据设备的UUID或名称过滤扫描结果。 3. 连接设备:Android BLE工具类可以连接指定的BLE设备,并提供连接成功、连接失败、断开连接等回调方法,方便开发者处理连接状态。 4. 发现服务和特征值:Android BLE工具类支持发现BLE设备的服务和特征值,通过服务和特征值,开发者可以读取、写入及监听BLE设备的数据。 5. 数据操作:Android BLE工具类可以进行BLE设备的数据读取、写入及监听操作,开发者可以根据实际需求进行相应的数据处理。 6. 错误处理:Android BLE工具类提供BLE操作过程中可能发生的错误处理方法,开发者可以根据错误码进行相应的处理,以增强应用的稳定性。 总的来说,Android BLE工具类简化了与BLE设备的通信操作,提供了易于使用的API接口,方便开发者快速开发与蓝牙低功耗设备的交互功能。但是对于复杂的BLE设备通信需求,可能需要根据实际情况自行进行定制和扩展。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小北编程

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值