Flutter日期时间格式化插件humanizer的使用

Flutter日期时间格式化插件humanizer的使用

Humanizer

pub package All Contributors

Humanizer 是一个Dart库,用于将值转换为对用户友好的表示形式。它具有广泛的API表面,并且有多个API层。以下是对日期时间格式化的详细介绍和示例代码。

什么是Humanizer?

当编写用户界面时,我们经常希望以一种对最终用户有意义的方式呈现原始格式的数据,但这通常并不简单。此库旨在使这些转换变得容易和灵活。

安装与导入

首先,安装 humanizer 包,然后你可以通过如下方式在Dart代码中导入Humanizer:

import 'package:humanizer/humanizer.dart';

功能概述

Feature Description
Approximate time Duration 转换为对人类友好的近似时间描述

使用示例

Approximate Time(近似时间)

下面是一个简单的例子,展示了如何使用Humanizer来格式化日期时间:

import 'package:humanizer/humanizer.dart';

void main() {
  _approximateTime();
}

void _approximateTime() {
  print("Duration.zero.toApproximateTime() => '${Duration.zero.toApproximateTime()}'");
  print("const Duration(seconds: 28).toApproximateTime() => '${const Duration(seconds: 28).toApproximateTime()}'");
  print("const Duration(seconds: -28).toApproximateTime() => '${const Duration(seconds: -28).toApproximateTime()}'");
  print("const Duration(hours: 2, minutes: 40).toApproximateTime() => '${const Duration(hours: 2, minutes: 40).toApproximateTime()}'");
  print("const Duration(hours: 2, minutes: 40).toApproximateTime(round: false) => '${const Duration(hours: 2, minutes: 40).toApproximateTime(round: false)}'");
  print("const Duration(hours: 2, minutes: 40).toApproximateTime(granularity: Granularity.primaryAndSecondaryUnits) => '${const Duration(hours: 2, minutes: 40).toApproximateTime(granularity: Granularity.primaryAndSecondaryUnits)}'");
}

完整示例Demo

这里提供一个完整的Flutter应用示例,演示如何在Flutter应用中使用Humanizer进行日期时间格式化:

import 'package:flutter/material.dart';
import 'package:humanizer/humanizer.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(title: 'Flutter Date Time Format'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  String formattedTime = '';

  void _formatTime() {
    final now = DateTime.now();
    final past = now.subtract(Duration(days: 2, hours: 3, minutes: 45));
    final duration = now.difference(past);
    setState(() {
      formattedTime = duration.toApproximateTime();
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(
              'Formatted Time:',
            ),
            Text(
              '$formattedTime',
              style: Theme.of(context).textTheme.headline4,
            ),
            SizedBox(height: 20),
            ElevatedButton(
              onPressed: _formatTime,
              child: Text('Format Time'),
            ),
          ],
        ),
      ),
    );
  }
}

这个示例展示了如何在按下按钮后格式化当前时间和过去时间之间的差异,并显示一个对人类友好的时间描述。希望这能帮助你更好地理解和使用Humanizer插件!


更多关于Flutter日期时间格式化插件humanizer的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter日期时间格式化插件humanizer的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


在Flutter项目中,使用humanizer插件可以帮助你更便捷地进行日期和时间的格式化。以下是一个简单的示例,展示如何在Flutter中使用humanizer插件来格式化日期和时间。

首先,确保你已经在pubspec.yaml文件中添加了humanizer插件的依赖:

dependencies:
  flutter:
    sdk: flutter
  humanizer: ^x.y.z  # 请替换为当前最新版本号

然后,运行flutter pub get来安装依赖。

接下来,你可以在你的Dart代码中使用humanizer插件。以下是一个完整的示例,展示如何格式化当前日期和时间:

import 'package:flutter/material.dart';
import 'package:humanizer/humanizer_dart.dart' as humanizer;
import 'package:intl/intl.dart';  // 用于获取当前日期和时间

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Humanizer Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  @override
  Widget build(BuildContext context) {
    // 获取当前日期和时间
    DateTime now = DateTime.now();
    
    // 使用 humanizer 插件格式化日期和时间
    String formattedDate = humanizer.DateHumanize.fromNow(now);
    String formattedDateTime = humanizer.DateTimeHumanize.fromNow(now);
    String timeAgo = humanizer.DateHumanize.timeAgo(now, allowFromNow: false);
    String dateTimeFormatted = DateFormat('yyyy-MM-dd HH:mm:ss').format(now);

    return Scaffold(
      appBar: AppBar(
        title: Text('Flutter Humanizer Demo'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(
              '当前日期和时间: $dateTimeFormatted',
              style: TextStyle(fontSize: 18),
            ),
            SizedBox(height: 20),
            Text(
              '从现在开始: $formattedDate',
              style: TextStyle(fontSize: 18),
            ),
            SizedBox(height: 20),
            Text(
              '从现在开始 (包括时间): $formattedDateTime',
              style: TextStyle(fontSize: 18),
            ),
            SizedBox(height: 20),
            Text(
              '多久之前: $timeAgo',
              style: TextStyle(fontSize: 18),
            ),
          ],
        ),
      ),
    );
  }
}

在这个示例中,我们:

  1. 使用DateTime.now()获取当前的日期和时间。
  2. 使用humanizer.DateHumanize.fromNowhumanizer.DateTimeHumanize.fromNow方法将当前日期和时间格式化为相对时间(例如,“2分钟前”、“3小时前”等)。
  3. 使用humanizer.DateHumanize.timeAgo方法将当前日期和时间格式化为更具体的相对时间,但不包括“从现在开始”的表述。
  4. 使用intl包中的DateFormat类将当前日期和时间格式化为标准的“yyyy-MM-dd HH:mm:ss”格式。

这样,你就可以在你的Flutter应用中方便地使用humanizer插件来格式化日期和时间了。

回到顶部