dart時間處理的幾個方法


一、時間處理的方法

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---------------

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM