一、獲取當前時間spa
var now = new DateTime.now(); print(now); // 2019-06-20 16:59:05.560543
二、設置時間code
var d =new DateTime(2019, 6, 20, 16, 37 , 26); print(d); // 2019-06-20 16:37:26.000
三、建立時間UTCblog
var ds = new DateTime.utc(2019, 10, 10, 9, 30); print(ds); // 2019-10-10 09:30:00.000Z
四、解析時間字符串
var d1 = DateTime.parse('2018-10-10 09:30:36'); print(d1); // 2018-10-10 09:30:36.000 var d2 = DateTime.parse('2018-10-10 09:30:30+0800'); print(d2); // 2018-10-10 01:30:30.000Z
五、時間加減io
print(now.add(new Duration(minutes: 10)));//加10分鐘 2019-06-20 17:09:05.560543 print(now.add(new Duration(minutes: -10)));//減10分鐘 2019-06-20 16:49:05.560543 print(now.add(new Duration(hours: 2)));//加2小時 2019-06-20 18:59:05.560543 print(now.add(new Duration(hours: -2)));//減2小時 2019-06-20 14:59:05.560543
六、比較時間class
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
七、計算時間差im
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]
八、時間戳時間戳
print(now.millisecondsSinceEpoch);//單位毫秒,13位時間戳 1561021145560 print(now.microsecondsSinceEpoch);//單位微秒,16位時間戳 1561021145560543
九、打印當前時間d3
// padLeft(int width,String sring):若是字符串長度小於width,在左邊填充sring print("${now.year.toString()}-${now.month.toString().padLeft(2,'0')}-${now.day.toString().padLeft(2,'0')} ${now.hour.toString().padLeft(2, '0')}:${now.minute.toString().padLeft(2, '0')}:${now.second.toString().padLeft(2, '0')}"); // 2019-06-20 16:59:05