Flutter中的日期和时间戳前端
//獲取當前日期
DateTime _nowDate = DateTime.now();
print(_nowDate);//2019-10-29 10:57:20.384872
print(_nowDate.millisecondsSinceEpoch);//時間戳,1572317840384
print(DateTime.fromMicrosecondsSinceEpoch(1572317840384));//時間戳轉換日期,1970-01-19 12:45:17.840384
所谓时间戳,是指自格林威治时间1970年01月01日00时00分00秒(北京时间1970年01月01日08时00分00秒)起至如今的总秒数。async
有些状况下,后台可能会将全部的时间都转换成时间戳返回给咱们前端,这是咱们就须要将时间戳转换成时间,并将时间进行格式化。this
展现一个时间,咱们会有多种形式,好比1970-01-0一、1970/01/0一、1970年01月01日,等等,那么咱们如何把同一个时间根据须要转换成不一样的格式呢?接下来我就为你们介绍一个Flutter中的第三方库。spa
Flutter第三方組件庫code
登陸pub.dev搜索date_format組件查看Installing添加依賴orm
pubspec.yamlblog
dependencies: date_format: ^1.0.8
按ctrl+s或flutter packages get後會自動下載依賴包,注意控制台,如無異常就是下載成功事件
引入包ci
import 'package:date_format/date_format.dart';
print(formatDate(DateTime.now(), [yyyy, "-", mm, "-", dd, " ", DD, " ", HH, ":", nn, ":", ss]));
輸出get
2019-10-29 Wednesday 14:27:29
调用Flutter自带的日期选择器组件和时间选择器组件
顯示日曆組件和獲取選中數據的方法一
//_表明私有,重寫私有的日曆組建 _showDatePicker(){ showDatePicker( context:context,//上下文必須傳入 initialDate:_nowDate,//設置初始化日期 firstDate:DateTime(1900),//設置起始時間 lastDate: DateTime(2100),//設置結束時間 ).then((val){//異步方法 print(val); }); }
方法二
_showDatePicker() async{ var val = await showDatePicker( context:context,//上下文必須傳入 initialDate:_nowDate,//設置初始化日期 firstDate:DateTime(1900),//設置起始時間 lastDate: DateTime(2100),//設置結束時間 ); setState(() { //將獲得時間傳給變量 this._nowDate =val; }); }
使用變量替換文本
Container(
margin: EdgeInsets.all(5),
width: 350,
height: 120,
decoration: new BoxDecoration(
color: Colors.black12,
borderRadius:BorderRadius.circular(10.0),//邊框
),
child: GestureDetector(//手勢事件
child: Text('${formatDate(_nowDate, [yyyy, "-", mm, "-", dd])}'),//替換文本
onTap: (){
_showDatePicker();//調用重寫的組件
},
),
),
時間
//自帶組件
showTimePicker( context: context, initialTime: new TimeOfDay.now(), ).then((val) { print(val); }).catchError((err) { print(err); });
//獲得當前時間 var _nowTime = TimeOfDay.now(); _showTimePicker() async{ var val = await showTimePicker( context: context,//上下文 initialTime: _nowTime//當前時間,設置固定時間TimeOfDay(hour: 12,minute: 10) ); setState(() { this._nowTime = val; }); }