Flutter中的日期和时间戳
//獲取當前日期
DateTime _nowDate = DateTime.now();print(_nowDate);//2019-10-29 10:57:20.384872print(_nowDate.millisecondsSinceEpoch);//時間戳,1572317840384print(DateTime.fromMicrosecondsSinceEpoch(1572317840384));//時間戳轉換日期,1970-01-19 12:45:17.840384所谓时间戳,是指自格林威治时间1970年01月01日00时00分00秒(北京时间1970年01月01日08时00分00秒)起至现在的总秒数。
有些情况下,后台可能会将所有的时间都转换成时间戳返回给我们前端,这是我们就需要将时间戳转换成时间,并将时间进行格式化。
展示一个时间,我们会有多种形式,比如1970-01-01、1970/01/01、1970年01月01日,等等,那么我们如何把同一个时间根据需要转换成不同的格式呢?接下来我就为大家介绍一个Flutter中的第三方库。
Flutter第三方組件庫
登陸pub.dev搜索date_format組件查看Installing添加依賴
pubspec.yaml
dependencies:
    date_format: ^1.0.8按ctrl+s或flutter packages get後會自動下載依賴包,注意控制台,如無異常就是下載成功
引入包
import 'package:date_format/date_format.dart';print(formatDate(DateTime.now(), [yyyy, "-", mm, "-", dd, " ", DD, " ", HH, ":", nn, ":", ss]));輸出
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;
    });
  }
參考:https://cloud.tencent.com/developer/article/1495839
来源:oschina
链接:https://my.oschina.net/u/4298384/blog/3360095