Android开发,时间格式化工具TimeAgoUtils

主要用于将时间转换成类似微信、微博等社交媒体常见的"多久之前"的格式

1. 主要功能分析

这个类包含一个核心方法timeAgo,将日期时间转换成以下几种人性化格式:

  • 1分钟内:显示"刚刚"
  • 1小时内:显示"XX分钟前"
  • 24小时内:显示具体时间(如"14:30")
  • 30天内:显示具体日期(如"3月15日")
  • 365天内:显示"XX个月前"
  • 365天以上:显示"XX年前"

2. 使用场景

  • 社交媒体评论时间显示
  • 消息列表时间显示
  • 动态更新时间显示
  • 新闻发布时间显示

3. 代码实现过程

public class TimeAgoUtils {

    @SuppressLint("NewApi")
    private static final DateTimeFormatter TIME_FORMATTER = DateTimeFormatter.ofPattern("HH:mm");

    /**
     * 根据给定的日期,返回“刚刚”或“多久前”的字符串表示。
     * @param dateTimeString 给定的日期
     * @return “刚刚”或“多久前”的字符串
     */
    @SuppressLint("NewApi")
    public static String timeAgo(String dateTimeString) {
        if (dateTimeString == null) {
            throw new IllegalArgumentException("Date cannot be null");
        }
        Instant now = Instant.now();
        // 定义日期时间格式
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
        // 将字符串解析为 LocalDateTime
        LocalDateTime localDateTime = LocalDateTime.parse(dateTimeString, formatter);
        // 将 LocalDateTime 转换为 Date
        Date date = Date.from(localDateTime.atZone(ZoneId.systemDefault()).toInstant());
        Instant then = date.toInstant();
        long seconds = Duration.between(then, now).getSeconds();

        if (seconds < 60) {
            return "刚刚";
        } else if (seconds < 3600) {
            long minutes = seconds / 60;
            return minutes + "分钟前";
        } else if (seconds < 86400) { // 1天内
            LocalDateTime localThen = LocalDateTime.ofInstant(then, ZoneId.systemDefault());
            return localThen.format(TIME_FORMATTER);
        } else if (seconds < 2592000) { // 30天
            LocalDateTime localThen = LocalDateTime.ofInstant(then, ZoneId.systemDefault());
            int month = localThen.getMonthValue();
            int day = localThen.getDayOfMonth();
            return month + "月" + day + "日";
        } else if (seconds < 31104000) { // 365天
            long months = seconds / 2592000;
            return months + "个月前";
        } else {
            long years = seconds / 31104000;
            return years + "年前";
        }
    }
}

这种时间显示方式更加直观友好,让用户能够快速理解内容的时效性。

4. 使用示例

// 假设评论时间是 "2024-03-20 14:30"
String commentTime = "2024-03-20 14:30";
String formattedTime = TimeAgoUtils.timeAgo(commentTime);
// 根据当前时间的不同,可能显示:
// - "刚刚"
// - "5分钟前"
// - "14:30"
// - "3月20日"
// - "1个月前"
// - "1年前"

5. 效果图

在这里插入图片描述

6. 关于作者其它项目视频教程介绍

本人在b站录制的一些视频教程项目,免费供大家学习

  1. Android新闻资讯app实战:https://www.bilibili.com/video/BV1CA1vYoEad/?vd_source=984bb03f768809c7d33f20179343d8c8
  2. Androidstudio开发购物商城实战:https://www.bilibili.com/video/BV1PjHfeXE8U/?vd_source=984bb03f768809c7d33f20179343d8c8
  3. Android开发备忘录记事本实战:https://www.bilibili.com/video/BV1FJ4m1u76G?vd_source=984bb03f768809c7d33f20179343d8c8&spm_id_from=333.788.videopod.sections
  4. Androidstudio底部导航栏实现:https://www.bilibili.com/video/BV1XB4y1d7et/?spm_id_from=333.337.search-card.all.click&vd_source=984bb03f768809c7d33f20179343d8c8
  5. Android使用TabLayout+ViewPager2实现左右滑动切换:https://www.bilibili.com/video/BV1Mz4y1c7eX/?spm_id_from=333.337.search-card.all.click&vd_source=984bb03f768809c7d33f20179343d8c8
### Android 平台上记事本应用开发教程 #### 创建项目结构 为了创建一个简单的记事本应用程序,首先需要设置项目的初始配置。打开 Android Studio 后,选择 `New Project` 来启动一个新的项目向导。 #### 设计用户界面 (UI) 设计简洁明了的 UI 是至关重要的。可以使用 XML 文件来定义布局,在此过程中可利用 RecyclerView 或 ListView 控件展示笔记列表[^1]。 ```xml <!-- res/layout/activity_main.xml --> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent"> <!-- 添加编辑框用于输入新笔记 --> <EditText android:id="@+id/noteInput" android:hint="Enter your note here..." android:padding="16dp" android:textSize="18sp"/> <!-- 列表视图用来显示已保存的笔记 --> <ListView android:id="@+id/notesList" android:layout_width="match_parent" android:layout_height="wrap_content"/> </LinearLayout> ``` #### 实现数据存储功能 对于持久化的数据管理,SQLite 数据库是一个不错的选择。通过 ContentProvider 可以使其他组件访问这些数据。 ```java // NoteDatabaseHelper.java public class NoteDatabaseHelper extends SQLiteOpenHelper { private static final int DATABASE_VERSION = 1; private static final String DATABASE_NAME = "Notes.db"; public static final String TABLE_NOTES = "notes"; // 构造函数... } ``` #### 处理 Activity 生命周期方法 确保每个活动都正确处理其生命周期事件非常重要。特别是当 activity 设置为 `android:exported=true` 时,意味着该 activity 允许被外部应用调用。 ```xml <!-- AndroidManifest.xml 中的部分内容 --> <activity android:name=".MainActivity" android:exported="true"> ... </activity> ``` #### 时间格式化工具的应用 为了让用户体验更佳,可以在记录每条笔记的时间戳上采用友好的时间表示形式。例如,使用自定义的时间格式化工具TimeAgoUtils 将绝对时间转换成相对描述性的字符串[^3]。 ```java String currentTime = new SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.getDefault()).format(new Date()); note.setTime(currentTime); TextView timeView = findViewById(R.id.note_time); timeView.setText(TimeAgoUtils.timeAgo(note.getTime())); ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

浩宇软件开发

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

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

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

打赏作者

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

抵扣说明:

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

余额充值