API: https://api.dart.dev/stable/2.10.3/dart-core/DateTime-class.html

constructor

DateTime

通过 DateTime 实例进行解析, 可以接收8个参数,第一个是年份必填,剩余的是选填,如下:

  1. /**
  2. * DateTime(int year,
  3. * [int month = 1,
  4. * int day = 1,
  5. * int hour = 0,
  6. * int minute = 0,
  7. * int second = 0,
  8. * int millisecond = 0,
  9. * int microsecond = 0])
  10. */
  11. // 默认获取的是本地时间
  12. print(DateTime(2020, 11, 04, 9, 30)); //2020-11-04 09:30:00.000
  13. print(DateTime(2020, 11, 04, 9, 30).toLocal()); //2020-11-04 09:30:00.000

now 获取当前时间

  1. var s1 = DateTime.now(); //等同于:var s1 = new DateTime.now();
  2. print(s1); //2020-11-04 15:16:07.579148
  3. print(s1.runtimeType); //DateTime

utc 获取utc时间

  1. print(DateTime.utc(2020, 11, 04, 9, 30)); //2020-11-04 09:30:00.000Z
  2. print(DateTime.utc(2020, 11, 04, 9, 30).toLocal()); //2020-11-04 17:30:00.000

fromMillisecondsSinceEpoch、fromMicrosecondsSinceEpoch

  1. var s1 = DateTime(2020, 11, 04, 09, 20, 40, 432, 789);
  2. print(s1); //2020-11-04 09:20:40.432789
  3. var millisecondsSinceEpoch = s1.millisecondsSinceEpoch;
  4. var microsecondsSinceEpoch = s1.microsecondsSinceEpoch;
  5. print(millisecondsSinceEpoch); //1604452840432 获取13位毫秒数
  6. print(microsecondsSinceEpoch); //1604452840432789 获取16位微秒数
  7. print(DateTime.fromMillisecondsSinceEpoch(millisecondsSinceEpoch));
  8. //2020-11-04 09:20:40.432
  9. print(DateTime.fromMicrosecondsSinceEpoch(microsecondsSinceEpoch));
  10. //2020-11-04 09:20:40.432789

TimeOfDay

  1. print(TimeOfDay.now()); //TimeOfDay(17:36)
  2. print(TimeOfDay.fromDateTime(DateTime.now())); //TimeOfDay(17:36)
  3. print(TimeOfDay(hour: 15, minute: 04)); //TimeOfDay(15:04)
  4. print(TimeOfDay.now().format(context)); //5:36 PM
  5. print(TimeOfDay.now().toString().substring(10, 15)); //17:36

Static methods 类的静态方法

parse 解析日期

https://api.dart.dev/stable/2.10.3/dart-core/DateTime/parse.html
参数接收一个字符串, 能够被解析的有以下格式:

  • "2012-02-27"
  • "2012-02-27 13:27:00"
  • "2012-02-27 13:27:00.123456789z"
  • "2012-02-27 13:27:00,123456789z"
  • "20120227 13:27:00"
  • "20120227T132700"
  • "20120227"
  • "+20120227"
  • "2012-02-27T14Z"
  • "2012-02-27T14+00:00"
  • "-123450101 00:00:00 Z": in the year -12345.
  • "2002-02-27T14:00:00-0500": Same as "2002-02-27T19:00:00Z" ```dart

print(DateTime.parse(‘2020-11-04 09:30:04’)); //2020-11-04 09:30:04.000 print(DateTime.parse(‘2020-11-04 09:30:04+0800’)); //2020-11-04 01:30:04.000Z

  1. <a name="wzFFY"></a>
  2. ## tryParse parse的语法糖
  3. 如果接收的参数无法被解析那么不会抛出异常,而是返回 null 。
  4. 内部实现原理:
  5. ```dart
  6. try {
  7. return parse(formattedString);
  8. } on FormatException {
  9. return null;
  10. }

属性

  1. var s1 = DateTime.now();
  2. print(s1); //2020-11-04 15:30:59.621947
  3. print(s1.year); //2020 年
  4. print(s1.month); //11 月(1-12,与js不一样)
  5. print(s1.day); //4 天 (1-31)
  6. print(s1.hour); //15 时 (0-23)
  7. print(s1.minute); //30 分 (0-59)
  8. print(s1.second); //59 秒 (0-59)
  9. print(s1.millisecond); //621 毫秒 (0-999)
  10. print(s1.millisecondsSinceEpoch); //1604475059621 获取13位毫秒时间戳
  11. print(s1.microsecond); //947 微秒 (0-999)
  12. print(s1.microsecondsSinceEpoch); //1604475059621947 获取16位微秒时间戳
  13. print(s1.weekday); //3 星期几(1-7)
  14. print(s1.timeZoneName); //'中国标准时间' 时区名字
  15. print(s1.timeZoneOffset); //8:00:00.000000 时区的偏移时差(北京时区是东八区,领先UTC八个小时)
  16. print(s1.isUtc); //false 是否是UTC时间
  17. print(s1.hashCode); //904666416 hash码

方法

add 添加时间

通过添加时间来改变原始的 DateTime,参数接收的是 Duration 类型。

  1. var s1 = DateTime(2020, 11, 04, 09, 20, 40);
  2. print(s1); //2020-11-04 09:20:40.000
  3. // 加5分钟
  4. print(s1.add(new Duration(minutes: 5))); //2020-11-04 09:25:40.000
  5. print(s1.add(new Duration(minutes: -5))); //2020-11-04 09:15:40.000
  6. // 加10小时
  7. print(s1.add(new Duration(hours: 10))); //2020-11-04 19:20:40.000
  8. print(s1.add(new Duration(hours: -10))); //2020-11-03 23:20:40.000

subtract 减少时间

add的反向操作。

  1. var s1 = DateTime(2020, 11, 04, 09, 20, 40);
  2. print(s1); //2020-11-04 09:20:40.000
  3. // 减 5分钟
  4. print(s1.subtract(new Duration(minutes: 5))); //2020-11-04 09:15:40.000
  5. print(s1.subtract(new Duration(minutes: -5))); //2020-11-04 09:25:40.000
  6. // 减 10小时
  7. print(s1.subtract(new Duration(hours: 10))); //2020-11-03 23:20:40.000
  8. print(s1.subtract(new Duration(hours: -10))); //2020-11-04 19:20:40.000

isBefore、isAfter、compareTo、isAtSameMomentAs 比较时间

  • **isBefore** 检查一个 DateTime 是否在另一个 DateTime 之前
  • **isAfter** 检查一个 DateTime 是否在另一个 DateTime 之后
  • **compareTo** 判断2个 DateTime 是否相等,如果相等则返回 0 否则 -1
  • **isAtSameMomentAs** 如果此事件与other同时发生,则返回true ```dart var s1 = DateTime(2020, 11, 11, 6, 10, 20); var s2 = DateTime(2020, 11, 12, 10, 20, 10);

print(s1.isBefore(s2)); //true 时间是否早于参数 print(s1.isAfter(s2)); //false 时间是否晚于参数

print(s1.compareTo(s2)); //-1 时间早于参数,返回-1; print(s1.compareTo(s1)); //0 时间相同,返回0; print(s2.compareTo(s1)); //1 时间晚于参数,返回1;

// s4、s4是同一时间,但是是不同的时区 var s3 = DateTime.utc(2020, 11, 04, 9, 30); var s4 = s3.toLocal();

// 比较时间是否相同 print(s3 == s4); //false print(s3.isAtSameMomentAs(s4)); //true

  1. <a name="U45T3"></a>
  2. ## difference 时间差
  3. ```dart
  4. var s1 = DateTime(2020, 11, 11, 6, 10, 20);
  5. var s2 = DateTime(2020, 11, 12, 10, 20, 10);
  6. var diff = s1.difference(s2);
  7. print(diff); //-28:09:50.000000 s1比s2早了 28:09:50.000000
  8. print([diff.inDays, diff.inHours, diff.inMinutes]); //[-1, -28, -1689] 相差的天数、小时数、分钟数

toString、toIso8601String、toLocal、toUtc

  • toString 要把一个 DateTime 转换成时间可以使用 toString 方法
  • toIso8601String 转换成 ISO 8601toIso8601String-API
  • toLocal 在本地时区返回此DateTime值
  • toUtc 在UTC时区中返回此DateTime值 ```dart var s1 = DateTime(2020, 11, 04, 09, 20, 40, 432, 789);

print(s1); //2020-11-04 09:20:40.432789 print(s1.toString()); //2020-11-04 09:20:40.432789 print(s1.toIso8601String()); //2020-11-04T09:20:40.432789 print(s1.toLocal()); //2020-11-04 09:20:40.432789 print(s1.toUtc()); //2020-11-04 01:20:40.432789Z

  1. <a name="frM0i"></a>
  2. # 常用封装方法
  3. <a name="XIQhC"></a>
  4. ## 补零
  5. ```dart
  6. formatNumber(n, [m = 2]) {
  7. return n.toString().padLeft(m, '0');
  8. }
  9. print('${formatNumber(1)} -- ${formatNumber(12)} -- ${formatNumber(123)}');
  10. //01 -- 12 -- 123
  11. print('${formatNumber(1, 3)} -- ${formatNumber(12, 3)} -- ${formatNumber(123, 3)}');
  12. //001 -- 012 -- 123
  13. String _digits(int value, int length) {
  14. String ret = '$value';
  15. if (ret.length < length) {
  16. ret = '0' * (length - ret.length) + ret;
  17. }
  18. return ret;
  19. }
  20. print(_digits(2, 2)); //02
  21. print(_digits(2, 3)); //002
  22. print(_digits(21, 2)); //21
  23. print(_digits(21, 3)); //021

获取简单时间

  1. var s1 = DateTime(2020, 11, 04, 09, 20, 40, 432, 789);
  2. print(s1); //2020-11-04 09:20:40.432789
  3. var millisecondsSinceEpoch = s1.millisecondsSinceEpoch;
  4. print(millisecondsSinceEpoch); //1604452840432
  5. formatNumber(n, [m = 2]) {
  6. return n.toString().padLeft(m, '0');
  7. }
  8. formateTimeSimple(time, [hasTime = false, sep = "-"]) {
  9. var date = DateTime.fromMillisecondsSinceEpoch(time);
  10. var year = date.year;
  11. var month = date.month;
  12. var day = date.day;
  13. var hour = date.hour;
  14. var minute = date.minute;
  15. if (hasTime) {
  16. return '${[year, month, day].map(formatNumber).join(sep)} ${[hour, minute].map(formatNumber).join(":")}';
  17. } else {
  18. return '${[year, month, day].map(formatNumber).join(sep)}';
  19. }
  20. }
  21. print(formateTimeSimple(millisecondsSinceEpoch)); //2020-11-04
  22. print(formateTimeSimple(millisecondsSinceEpoch, true)); //2020-11-04 09:20
  23. print(formateTimeSimple(millisecondsSinceEpoch, true, '.')); //2020.11.04 09:20

库 date_format

https://pub.dev/packages/date_format

  1. import 'package:date_format/date_format.dart';
  2. void main() {
  3. var date = DateTime(1989, 02, 11, 15, 04, 10, 765);
  4. // 1989年 => yyyy 1989; yy 89
  5. // 02月 => mm 02; m 2; MM February; M Feb
  6. // 11日 => dd 11; d 11;
  7. // 15时 => HH 15; H 15; hh 03; h 3
  8. // 04分 => nn 04; n 4
  9. // 10时 => ss 10; s 10
  10. // 765秒 => SSS 765
  11. // 周几 => DD Saturday; D Sat
  12. // 时区 => z +0800; Z 中国标准时间
  13. // 上下午 => am (下午15点 -> PM;早上5点 -> AM)
  14. //w 2(本月的第几周);WW 06(本年的第几周) 注意: 周二算是每周的第一天
  15. print(formatDate(date, ['yyyy', '-', 'mm', '-', 'DD'])); //1989-02-11
  16. print(formatDate(date, [yyyy, '-', mm, '-', DD])); //1989-02-11
  17. print(formatDate(date, [yy, '-', m, '-', D])); //89-2-11
  18. print(formatDate(date, [HH, ':', nn, ':', ss])); //15:04:10
  19. print(formatDate(date, [H, ':', n, ':', s])); //15:4:10
  20. print(formatDate(date, [H, ':', n, ':', s, z])); //15:4:10+0800
  21. print(formatDate(date, [w, '--', WW])); //2--06
  22. }