第四百一十回

文章目录

  • [1. 概念介绍](#1. 概念介绍)
  • [2. 方法与细节](#2. 方法与细节)
    • [2.1 获取方法](#2.1 获取方法)
    • [2.2 使用细节](#2.2 使用细节)
  • [3. 示例代码](#3. 示例代码)
  • [4. 内容总结](#4. 内容总结)

我们在上一章回中介绍了"如何获取当前系统语言"相关的内容,本章回中将介绍如何获取时间戳.闲话休提,让我们一起Talk Flutter吧。

1. 概念介绍

我们在本章回中介绍的时间戳是指格林威治时间1970年01月01日00时00分00秒(北京时间1970年01月01日08时00分00秒)起至现在的总秒数。在实际项目中会使用

时间戳来签名或者做加密。本章回中将详细介绍获取时间戳的方法。

2. 方法与细节

2.1 获取方法

获取时间戳的方法主要通过DataTime类实现,直接通过类中的成员就可以获取到,该类提供了两种类型时间戳:毫秒和微秒,详细如下:

dart 复制代码
  /// The number of milliseconds since
  /// the "Unix epoch" 1970-01-01T00:00:00Z (UTC).
  ///
  /// This value is independent of the time zone.
  ///
  /// This value is at most
  /// 8,640,000,000,000,000ms (100,000,000 days) from the Unix epoch.
  /// In other words: `millisecondsSinceEpoch.abs() <= 8640000000000000`.
  external int get millisecondsSinceEpoch;

  /// The number of microseconds since
  /// the "Unix epoch" 1970-01-01T00:00:00Z (UTC).
  ///
  /// This value is independent of the time zone.
  ///
  /// This value is at most
  /// 8,640,000,000,000,000,000us (100,000,000 days) from the Unix epoch.
  /// In other words: `microsecondsSinceEpoch.abs() <= 8640000000000000000`.
  ///
  /// Note that this value does not fit into 53 bits (the size of a IEEE double).
  /// A JavaScript number is not able to hold this value.
  external int get microsecondsSinceEpoch;

这是源代码中的内容,从中可以看出来它是一个十六位长度的数字,而且这个数字是基于当前时区的。

2.2 使用细节

正常的时间戳是以秒为单位的,我们获取到的是毫秒或者微秒,因此除以转换值就可以,比如毫秒1000可以转换成秒。我们获取到的时间戳是带时区的,如果不想在时间

戳中带时区,那么首先通过toUtc方法把时间转换成标准UTC时间,然后再从转换后的时间中获取时间戳。我们将在后面的小节中通过具体的代码来演示它的用法。

3. 示例代码

dart 复制代码
///获取带时区的时间戳
DateTime.now().millisecondsSinceEpoch;
///获取不带时区的时间戳
DateTime.now().toUtc().millisecondsSinceEpoch;

4. 内容总结

最后,我们对本章回的内容做一个全面的总结:

  • 使用DateTime类中的成员可以获取到时间戳;
  • 获取到的时间戳分毫秒级和微秒级两种类型;
  • 获取到的时间戳中带有时区信息;
    看官们,与"如何获取时间戳"相关的内容就介绍到这里,欢迎大家在评论区交流与讨论!
相关推荐
talk_81 个月前
通过相机来获取图片
数码相机·移动开发flutter
talk_85 个月前
第四百四十二回 再谈flutter_launcher_icons包
移动开发flutter·launcher_icon·修改桌面图标
talk_86 个月前
第二百二十三回
移动开发flutter
talk_86 个月前
第四百一十五回
移动开发flutter
talk_86 个月前
第三百九十九回
移动开发flutter
talk_86 个月前
第三百八十九回
移动开发flutter
talk_86 个月前
第三百八十五回
移动开发flutter
talk_87 个月前
第二百九十六回
前端·移动开发flutter
talk_88 个月前
第二百九十回
数码相机·移动开发flutter