DateTime对象是一个时间点。时区是 UTC 或本地时区。几乎每个数据上下文都需要准确的日期时间处理。 Dart在dart:core 中有很棒的内置类DateTime和 Duration 。它的一些用途是:
- 与日期时间进行比较和计算
- 获取日期时间的每一部分
- 使用不同的时区
- 测量时间跨度
例子:
Dart
void main(){
// Get the current date and time.
var now = DateTime.now();
print(now);
// Create a new DateTime with the local time zone.
var y2k = DateTime(2000); // January 1, 2000
print(y2k);
// Specify the month and day.
y2k = DateTime(2000, 1, 2); // January 2, 2000
print(y2k);
// Specify the date as a UTC time.
y2k = DateTime.utc(2000); // 1/1/2000, UTC
print(y2k);
// Specify a date and time in ms since the Unix epoch.
y2k = DateTime.fromMillisecondsSinceEpoch(946684800000,
isUtc: true);
print(y2k);
// Parse an ISO 8601 date.
y2k = DateTime.parse('2000-01-01T00:00:00Z');
print(y2k);
}
Dart
void main(){
// 1/1/2000, UTC
var y2k = DateTime.utc(2000);
print(y2k.millisecondsSinceEpoch == 946684800000);
// 1/1/1970, UTC
var unixEpoch = DateTime.utc(1970);
print(unixEpoch.millisecondsSinceEpoch == 0);
}
Dart
void main(){
var y2k = DateTime.utc(2000);
// Add one year.
var y2001 = y2k.add(Duration(days: 366));
print(y2001.year == 2001);
// Subtract 30 days.
var december2000 = y2001.subtract(Duration(days: 30));
assert(december2000.year == 2000);
print(december2000.month == 12);
// Calculate the difference between two dates.
// Returns a Duration object.
var duration = y2001.difference(y2k);
print(duration.inDays == 366); // y2k was a leap year.
}
输出:
2020-08-25 11:58:56.257
2000-01-01 00:00:00.000
2000-01-02 00:00:00.000
2000-01-01 00:00:00.000Z
2000-01-01 00:00:00.000Z
2000-01-01 00:00:00.000Z
日期的millisecondsSinceEpoch属性返回自“Unix 纪元”(UTC 时间 1970 年 1 月 1 日)以来的毫秒数。
例子:
Dart
void main(){
// 1/1/2000, UTC
var y2k = DateTime.utc(2000);
print(y2k.millisecondsSinceEpoch == 946684800000);
// 1/1/1970, UTC
var unixEpoch = DateTime.utc(1970);
print(unixEpoch.millisecondsSinceEpoch == 0);
}
输出:
true
true
Duration 类可用于计算两个日期之间的差异以及向前或向后移动日期。
例子:
Dart
void main(){
var y2k = DateTime.utc(2000);
// Add one year.
var y2001 = y2k.add(Duration(days: 366));
print(y2001.year == 2001);
// Subtract 30 days.
var december2000 = y2001.subtract(Duration(days: 30));
assert(december2000.year == 2000);
print(december2000.month == 12);
// Calculate the difference between two dates.
// Returns a Duration object.
var duration = y2001.difference(y2k);
print(duration.inDays == 366); // y2k was a leap year.
}
输出:
true
true
true