Skip to content

Dart 的 DateTime #81

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
huruji opened this issue Sep 15, 2019 · 0 comments
Open

Dart 的 DateTime #81

huruji opened this issue Sep 15, 2019 · 0 comments

Comments

@huruji
Copy link
Owner

huruji commented Sep 15, 2019

Dart 通过 DateTime 来处理时间,DateTime 构造函数可以可以根据传入的参数构造一个 DateTime 实例,DateTime.now 构造函数返回本地时区当前时间的 DateTime 对象.

DateTime(int year, [ int month = 1, int day = 1, int hour = 0, int minute = 0, int second = 0, int millisecond = 0, int microsecond = 0 ])

同时,Dart 也提供了 DateTime.utc 构造函数来构造一个 utc DateTime 对象:

DateTime.utc(int year, [ int month = 1, int day = 1, int hour = 0, int minute = 0, int second = 0, int millisecond = 0, int microsecond = 0 ])

DateTime 对象提供了获取档期时间对象的年份、月份、每个月的第几天、小时、星期几等属性,其中月份从1开始,星期从1开始(星期一为1,星期天为7)等:

  DateTime date = DateTime.now();

  print(date.day); // 15
  print(date.hashCode); // 326917132
  print(date.hour); // 21
  print(date.isUtc); // false
  print(date.microsecond); // 379
  print(date.minute); // 54
  print(date.month); // 9
  print(date.second); // 28
  print(date.timeZoneName); // CST
  print(date.timeZoneOffset); // 8:00:00.000000
  print(date.weekday); // 7
  print(date.year); // 2019

DateTime 对象同时提供了 add 方法来返回一个新的 DateTime 对象,add 方法接受一个 Duration 对象,因为 Duration 对象可以为负的,所以 add 方法可以返回一个之前时间的 DateTime 对象。

  DateTime nextDay = date.add(Duration(hours: 24));
  DateTime prevDay = date.add(Duration(hours: -24));
  print(nextDay.day); // 16
  print(prevDay.day); // 14

对比两个 DateTime 对象可以使用 compareTo 方法:

  print(prevDay.compareTo(nextDay)); // -1
  print(nextDay.compareTo(prevDay)); // 1
  print(prevDay.compareTo(prevDay)); // 0

更方便的方法是使用 isAfter isBefore isAtSameMomentAs 来对比是否比时间更晚、更早、相同。

  print(prevDay.isAfter(nextDay)); // false
  print(prevDay.isBefore(nextDay)); // true
  print(prevDay.isAtSameMomentAs(prevDay)); // true

当然如果需要更详细的两个时间对比,使用 difference 方法可以返回两个 DateTime 对象的时间差,是一个 Duration 对象:

  print(prevDay.difference(nextDay));

DateTime 对象同时提供了月份,星期的常量:

  print(DateTime.monday); // 1
  print(DateTime.april); // 4
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant