首页 > 其他 > 详细

dart时间处理的几个方法

时间:2020-11-30 12:01:52      阅读:55      评论:0      收藏:0      [点我收藏+]

一、时间处理的方法

1、获取当前时间

new DateTime.now();

 

2、设置时间

new DateTime(2020, 11, 11, 12, 37 , 36);

 

3、解析时间

DateTime.parse(2018-10-10 09:30:36);

 

4、时间加减

// 加10分钟
now.add(new Duration(minutes: 10))

// 减2小时
now.add(new Duration(hours: -2))

 

5、比较时间

var d3 = new DateTime(2019, 6, 20);
var d4 = new DateTime(2019, 7, 20);
var d5 = new DateTime(2019, 6, 20);

print(d3.isAfter(d4));//是否在d4之后 false
print(d3.isBefore(d4));//是否在d4之前 true 
print(d3.isAtSameMomentAs(d5));//是否相同 true

 

6、计算时间差

var d6 = new DateTime(2019, 6, 19, 16 , 30);
var d7 = new DateTime(2019, 6, 20, 15, 20);
var difference = d7.difference(d6);
print([difference.inDays, difference.inHours,difference.inMinutes]);//d6与d7相差的天数与小时,分钟 [0, 22, 1370]

 

7、时间戳

print(now.millisecondsSinceEpoch);//单位毫秒,13位时间戳  1561021145560
print(now.microsecondsSinceEpoch);//单位微秒,16位时间戳  1561021145560543

 

二、一个例子

目标:输出发布时间

规则:小于一分钟,输出‘刚刚’;小于一小时,输出‘xx分钟前’;小于一天,输出‘xx小时前’;小于三天,输出‘xx天前’;大于三天,且在本年度内,输出‘xx月xx日’;大于三天,但不在本年度内,输出‘xx年xx月xx日’。

思路:先保证时间戳正确,然后比较当前时间和发布时间。

代码:

  String get publishTime {
    var now = new DateTime.now();
    var longTime = this.toString().length < 13 ? this * 1000 : this;
    var time = new DateTime.fromMillisecondsSinceEpoch(longTime);
    var difference = now.difference(time);
    int days = difference.inDays;
    int hours = difference.inHours;
    int minutes = difference.inMinutes;
    String result = ‘‘;
    if (days > 3) {
      bool isNowYear = now.year == time.year;
      var pattern = isNowYear ? MM-dd : yyyy-MM-dd;
      result = new DateFormat(pattern).format(time);
    } else if (days > 0) {
      result = $days天前;
    } else if (hours > 0) {
      result = $hours小时前;
    } else if (minutes > 0) {
      result = $minutes分钟前;
    } else {
      result = 刚刚;
    }
    return result;
  }

 

END---------------

 

dart时间处理的几个方法

原文:https://www.cnblogs.com/MaiJiangDou/p/14060017.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!