API: https://api.dart.dev/stable/2.10.3/dart-core/DateTime-class.html
constructor
DateTime
通过 DateTime
实例进行解析, 可以接收8个参数,第一个是年份必填,剩余的是选填,如下:
/**
* DateTime(int year,
* [int month = 1,
* int day = 1,
* int hour = 0,
* int minute = 0,
* int second = 0,
* int millisecond = 0,
* int microsecond = 0])
*/
// 默认获取的是本地时间
print(DateTime(2020, 11, 04, 9, 30)); //2020-11-04 09:30:00.000
print(DateTime(2020, 11, 04, 9, 30).toLocal()); //2020-11-04 09:30:00.000
now 获取当前时间
var s1 = DateTime.now(); //等同于:var s1 = new DateTime.now();
print(s1); //2020-11-04 15:16:07.579148
print(s1.runtimeType); //DateTime
utc 获取utc时间
print(DateTime.utc(2020, 11, 04, 9, 30)); //2020-11-04 09:30:00.000Z
print(DateTime.utc(2020, 11, 04, 9, 30).toLocal()); //2020-11-04 17:30:00.000
fromMillisecondsSinceEpoch、fromMicrosecondsSinceEpoch
var s1 = DateTime(2020, 11, 04, 09, 20, 40, 432, 789);
print(s1); //2020-11-04 09:20:40.432789
var millisecondsSinceEpoch = s1.millisecondsSinceEpoch;
var microsecondsSinceEpoch = s1.microsecondsSinceEpoch;
print(millisecondsSinceEpoch); //1604452840432 获取13位毫秒数
print(microsecondsSinceEpoch); //1604452840432789 获取16位微秒数
print(DateTime.fromMillisecondsSinceEpoch(millisecondsSinceEpoch));
//2020-11-04 09:20:40.432
print(DateTime.fromMicrosecondsSinceEpoch(microsecondsSinceEpoch));
//2020-11-04 09:20:40.432789
TimeOfDay
print(TimeOfDay.now()); //TimeOfDay(17:36)
print(TimeOfDay.fromDateTime(DateTime.now())); //TimeOfDay(17:36)
print(TimeOfDay(hour: 15, minute: 04)); //TimeOfDay(15:04)
print(TimeOfDay.now().format(context)); //5:36 PM
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
<a name="wzFFY"></a>
## tryParse parse的语法糖
如果接收的参数无法被解析那么不会抛出异常,而是返回 null 。
内部实现原理:
```dart
try {
return parse(formattedString);
} on FormatException {
return null;
}
属性
var s1 = DateTime.now();
print(s1); //2020-11-04 15:30:59.621947
print(s1.year); //2020 年
print(s1.month); //11 月(1-12,与js不一样)
print(s1.day); //4 天 (1-31)
print(s1.hour); //15 时 (0-23)
print(s1.minute); //30 分 (0-59)
print(s1.second); //59 秒 (0-59)
print(s1.millisecond); //621 毫秒 (0-999)
print(s1.millisecondsSinceEpoch); //1604475059621 获取13位毫秒时间戳
print(s1.microsecond); //947 微秒 (0-999)
print(s1.microsecondsSinceEpoch); //1604475059621947 获取16位微秒时间戳
print(s1.weekday); //3 星期几(1-7)
print(s1.timeZoneName); //'中国标准时间' 时区名字
print(s1.timeZoneOffset); //8:00:00.000000 时区的偏移时差(北京时区是东八区,领先UTC八个小时)
print(s1.isUtc); //false 是否是UTC时间
print(s1.hashCode); //904666416 hash码
方法
add 添加时间
通过添加时间来改变原始的 DateTime,参数接收的是 Duration 类型。
var s1 = DateTime(2020, 11, 04, 09, 20, 40);
print(s1); //2020-11-04 09:20:40.000
// 加5分钟
print(s1.add(new Duration(minutes: 5))); //2020-11-04 09:25:40.000
print(s1.add(new Duration(minutes: -5))); //2020-11-04 09:15:40.000
// 加10小时
print(s1.add(new Duration(hours: 10))); //2020-11-04 19:20:40.000
print(s1.add(new Duration(hours: -10))); //2020-11-03 23:20:40.000
subtract 减少时间
add的反向操作。
var s1 = DateTime(2020, 11, 04, 09, 20, 40);
print(s1); //2020-11-04 09:20:40.000
// 减 5分钟
print(s1.subtract(new Duration(minutes: 5))); //2020-11-04 09:15:40.000
print(s1.subtract(new Duration(minutes: -5))); //2020-11-04 09:25:40.000
// 减 10小时
print(s1.subtract(new Duration(hours: 10))); //2020-11-03 23:20:40.000
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
<a name="U45T3"></a>
## difference 时间差
```dart
var s1 = DateTime(2020, 11, 11, 6, 10, 20);
var s2 = DateTime(2020, 11, 12, 10, 20, 10);
var diff = s1.difference(s2);
print(diff); //-28:09:50.000000 s1比s2早了 28:09:50.000000
print([diff.inDays, diff.inHours, diff.inMinutes]); //[-1, -28, -1689] 相差的天数、小时数、分钟数
toString、toIso8601String、toLocal、toUtc
toString
要把一个DateTime
转换成时间可以使用toString
方法toIso8601String
转换成 ISO 8601 。 toIso8601String-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
<a name="frM0i"></a>
# 常用封装方法
<a name="XIQhC"></a>
## 补零
```dart
formatNumber(n, [m = 2]) {
return n.toString().padLeft(m, '0');
}
print('${formatNumber(1)} -- ${formatNumber(12)} -- ${formatNumber(123)}');
//01 -- 12 -- 123
print('${formatNumber(1, 3)} -- ${formatNumber(12, 3)} -- ${formatNumber(123, 3)}');
//001 -- 012 -- 123
String _digits(int value, int length) {
String ret = '$value';
if (ret.length < length) {
ret = '0' * (length - ret.length) + ret;
}
return ret;
}
print(_digits(2, 2)); //02
print(_digits(2, 3)); //002
print(_digits(21, 2)); //21
print(_digits(21, 3)); //021
获取简单时间
var s1 = DateTime(2020, 11, 04, 09, 20, 40, 432, 789);
print(s1); //2020-11-04 09:20:40.432789
var millisecondsSinceEpoch = s1.millisecondsSinceEpoch;
print(millisecondsSinceEpoch); //1604452840432
formatNumber(n, [m = 2]) {
return n.toString().padLeft(m, '0');
}
formateTimeSimple(time, [hasTime = false, sep = "-"]) {
var date = DateTime.fromMillisecondsSinceEpoch(time);
var year = date.year;
var month = date.month;
var day = date.day;
var hour = date.hour;
var minute = date.minute;
if (hasTime) {
return '${[year, month, day].map(formatNumber).join(sep)} ${[hour, minute].map(formatNumber).join(":")}';
} else {
return '${[year, month, day].map(formatNumber).join(sep)}';
}
}
print(formateTimeSimple(millisecondsSinceEpoch)); //2020-11-04
print(formateTimeSimple(millisecondsSinceEpoch, true)); //2020-11-04 09:20
print(formateTimeSimple(millisecondsSinceEpoch, true, '.')); //2020.11.04 09:20
库 date_format
https://pub.dev/packages/date_format
import 'package:date_format/date_format.dart';
void main() {
var date = DateTime(1989, 02, 11, 15, 04, 10, 765);
// 1989年 => yyyy 1989; yy 89
// 02月 => mm 02; m 2; MM February; M Feb
// 11日 => dd 11; d 11;
// 15时 => HH 15; H 15; hh 03; h 3
// 04分 => nn 04; n 4
// 10时 => ss 10; s 10
// 765秒 => SSS 765
// 周几 => DD Saturday; D Sat
// 时区 => z +0800; Z 中国标准时间
// 上下午 => am (下午15点 -> PM;早上5点 -> AM)
//w 2(本月的第几周);WW 06(本年的第几周) 注意: 周二算是每周的第一天
print(formatDate(date, ['yyyy', '-', 'mm', '-', 'DD'])); //1989-02-11
print(formatDate(date, [yyyy, '-', mm, '-', DD])); //1989-02-11
print(formatDate(date, [yy, '-', m, '-', D])); //89-2-11
print(formatDate(date, [HH, ':', nn, ':', ss])); //15:04:10
print(formatDate(date, [H, ':', n, ':', s])); //15:4:10
print(formatDate(date, [H, ':', n, ':', s, z])); //15:4:10+0800
print(formatDate(date, [w, '--', WW])); //2--06
}