Flutter中的日期、格式化日期、日期選擇器組件


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秒)起至現在的總秒數

有些情況下,后台可能會將所有的時間都轉換成時間戳返回給我們前端,這是我們就需要將時間戳轉換成時間,並將時間進行格式化。

展示一個時間,我們會有多種形式,比如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

 


免責聲明!

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



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