Flutter自带日期组件及第三方日期组件

日期和时间戳

Flutter中获取当前日期可以使用DateTime.now()进行获取。now.millisecondsSinceEpoch可以获取到时间戳
什么是时间戳

“时间戳是指格林威治时间1970年01月01日00时00分00秒(北京时间1970年01月01日08时00分00秒)起至现在的总秒数。通俗的讲, 时间戳是一份能够表示一份数据在一个特定时间点已经存在的完整的可验证的数据。

通俗点说就是将时间格式转换为通信及保存都很方便的格式,比如2020-08-15 15:07:17转化为时间戳(毫秒)1597475237894<-就是转化后的

日期转化成时间戳:

var now = new DateTime.now();
print(now.millisecondsSinceEpoch);//单位毫秒,13 位时间

时间戳转化成日期:

var now = new DateTime.now();
var a=now.millisecondsSinceEpoch; //时间戳
print(DateTime.fromMillisecondsSinceEpoch(a));
import 'package:flutter/material.dart';

class DatePickerDemo extends StatefulWidget {
    
    
  DatePickerDemo({
    
    Key? key}) : super(key: key);

  @override
  _DatePickerDemoState createState() => _DatePickerDemoState();
}

class _DatePickerDemoState extends State<DatePickerDemo> {
    
    
  var now = DateTime.now();
  @override
  void initState() {
    
    
    // TODO: implement initState
    super.initState();
    print(now.millisecondsSinceEpoch);
  }

  @override
  Widget build(BuildContext context) {
    
    
    return Scaffold(
      appBar: AppBar(
        title: Text("DatePicker"),
      ),
      body: ElevatedButton(
        child: Text("获取当前时间"),
        onPressed: () {
    
    
          print("当前时间为:$now");
          print("时间戳为:${now.millisecondsSinceEpoch}");
          print(
              DateTime.fromMillisecondsSinceEpoch(1642681440235));
        },
      ),
    );
  }
}

在这里插入图片描述

转为年月日格式

由上面结果我们可以看出DateTime.now()打印的结果为
2022-01-20 12:24:00.235260这种形式,如果我们想要转换成年月日的形式,可以用到第三方的库。第三方库的导入,我们在前面Dart学习时已经学习过,可以参考这篇文章,我们用到的库可以在这里找到https://pub.dev/packages/date_format/install
在这里插入图片描述
首先将date_format: ^2.0.5复制到我们项目的pubspec.yaml 文件下
在这里插入图片描述
复制完成点击ctrl+s保存,输出的地方会自动执行flutter pub get指令进行下载(没有执行的话手动输入执行),使用时在对应文件中导入包即可。
使用:

print(formatDate(DateTime.now(), [yyyy, '年', mm, '月', dd]));

这里就不放完整代码,输出结果:

I/flutter (16489): 当前时间为:2022-01-20 12:24:00.235260
I/flutter (16489): 时间戳为:1642681440235
I/flutter (16489): 20220120 //这个就是上面代码执行的结果

使用自带日期和时间组件

// ignore_for_file: prefer_const_literals_to_create_immutables, prefer_const_constructors, unnecessary_brace_in_string_interps, unnecessary_string_interpolations

import 'package:flutter/material.dart';
import 'package:date_format/date_format.dart';

class DatePickerDemo extends StatefulWidget {
    
    
  DatePickerDemo({
    
    Key? key}) : super(key: key);

  @override
  _DatePickerDemoState createState() => _DatePickerDemoState();
}

class _DatePickerDemoState extends State<DatePickerDemo> {
    
    
  var _nowDate = DateTime.now();
  var _nowTime = TimeOfDay(hour: 12, minute: 30);

  _showDatePicker() {
    
    
    showDatePicker(
            context: context,
            initialDate: _nowDate,
            firstDate: DateTime(1980),
            lastDate: DateTime(2100))
        .then((value) {
    
    
      print(value);
      setState(() {
    
    
        _nowDate = value!;
      });
    });
  }

  _showTimePicker() async {
    
    
    var result = await showTimePicker(context: context, initialTime: _nowTime);
    setState(() {
    
    
      _nowTime = result!;
    });
  }

  @override
  void initState() {
    
    
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    
    
    return Scaffold(
      appBar: AppBar(
        title: Text("DatePicker"),
      ),
      body: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              InkWell(
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    Text("${formatDate(_nowDate, [yyyy, '年', mm, '月', dd])}"),
                    Icon(Icons.arrow_drop_down),
                  ],
                ),
                onTap: _showDatePicker,
              ),
              InkWell(
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    Text("${_nowTime.format(context)}"),
                    Icon(Icons.arrow_drop_down),
                  ],
                ),
                onTap: _showTimePicker,
              )
            ],
          )
        ],
      ),
    );
  }
}

需要注意

  1. InkWell适合用来设置非按钮组件的事件回调,我们可以把它看成按钮,在内部使用onTap设置回调事件
  2. 主要的方法这些,下面两个方法,一个是设置日期(年月日),一个是设置时间(时分),这里用了两种方法来获取我们选择的日期(时间),一种是通过.then,另一种是通过异步,将方法用async修饰,然后内部通过await来获取值
 var _nowDate = DateTime.now();
  var _nowTime = TimeOfDay(hour: 12, minute: 30);

  _showDatePicker() {
    
    
    showDatePicker(
            context: context,
            initialDate: _nowDate,
            firstDate: DateTime(1980),
            lastDate: DateTime(2100))
        .then((value) {
    
    
      print(value);
      setState(() {
    
    
        _nowDate = value!;
      });
    });
  }

  _showTimePicker() async {
    
    
    var result = await showTimePicker(context: context, initialTime: _nowTime);
    setState(() {
    
    
      _nowTime = result!;
    });
  }

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

时间选择组件显示中文

由上图可知,时间选择组件为英文,我们要将其改为中文
参考TI营的文章http://bbs.itying.com/topic/5cfb2a12f322340b2c90e764

  1. 首先还是在pubspec.yaml 中引入
flutter_localizations:
    sdk: flutter

在这里插入图片描述

  1. 导入国际化的包 flutter_localizations
import 'package:flutter_localizations/flutter_localizations.dart'; 
  1. 在main中加入
import 'package:flutter_localizations/flutter_localizations.dart'; 
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
    
      
  
  @override
  Widget build(BuildContext context) {
    
    
    return MaterialApp(
      localizationsDelegates: [
        //此处
        GlobalMaterialLocalizations.delegate,
        GlobalWidgetsLocalizations.delegate,
      ],
      supportedLocales: [
        //此处
        const Locale('zh', 'CH'),
        const Locale('en', 'US'),
      ],
      locale: const Locale("zh"),
      home:DatePickerDemo(),
      onGenerateRoute: onGenerateRoute,
      
    );
  }
}

在这里插入图片描述
汉化后:
在这里插入图片描述

第三方时间组件

使用的第三方库的地址https://pub.dev/packages/flutter_datetime_picker/install
使用之前还是先在pubspec.yaml 中导入

dependencies:
  flutter_datetime_picker: ^1.5.1

在这里插入图片描述
导入时添加语句

import 'package:flutter_datetime_picker/flutter_datetime_picker.dart';

在这里插入图片描述
使用

// ignore_for_file: unnecessary_string_interpolations, prefer_const_constructors

import 'package:flutter/material.dart';
import 'package:flutter_datetime_picker/flutter_datetime_picker.dart';
import 'package:date_format/date_format.dart';

class DateTimePickerPage extends StatefulWidget {
    
    
  DateTimePickerPage({
    
    Key? key}) : super(key: key);

  @override
  _DateTimePickerPageState createState() => _DateTimePickerPageState();
}

class _DateTimePickerPageState extends State<DateTimePickerPage> {
    
    
  DateTime _nowDate = DateTime.now();
  DateTime _timeDate = DateTime.now();
  _showDatePicker() {
    
    
    DatePicker.showDatePicker(context,
        showTitleActions: true,
        //起始日期
        minTime: DateTime(2018, 3, 5),
        maxTime: DateTime(2022, 12, 31), onChanged: (date) {
    
    
      print('change $date');
    }, onConfirm: (date) {
    
    
      print('confirm $date');
      setState(() {
    
    
        _nowDate = date;
      });
    }, currentTime: DateTime.now(), locale: LocaleType.zh);
  }

  _showDateTimePicker() {
    
    
    DatePicker.showDateTimePicker(context,
        showTitleActions: true,
        minTime: DateTime(2020, 5, 5, 20, 50),
        maxTime: DateTime(2022, 12, 31, 05, 09), onChanged: (date) {
    
    
      print('change $date in time zone ' +
          date.timeZoneOffset.inHours.toString());
    }, onConfirm: (date) {
    
    
      print('confirm $date');
      setState(() {
    
    
        _timeDate = date;
      });
    }, locale: LocaleType.zh);
  }

  @override
  Widget build(BuildContext context) {
    
    
    return Scaffold(
      appBar: AppBar(
        title: Text("DatePicker"),
      ),
      body: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          InkWell(
            child: Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Text("${formatDate(_nowDate, [yyyy, '年', mm, '月', dd])}"),
                Icon(Icons.arrow_drop_down)
              ],
            ),
            onTap: _showDatePicker,
          ),
          SizedBox(height: 20),
          InkWell(
            child: Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Text("${formatDate(_timeDate, [yyyy,'-', mm,'-',dd," ",HH,':',nn,':',ss])}"),
                Icon(Icons.arrow_drop_down)
              ],
            ),
            onTap: _showDateTimePicker,
          )
        ],
      ),
    );
  }
}

// ignore_for_file: unnecessary_string_interpolations, prefer_const_constructors

import 'package:flutter/material.dart';
import 'package:flutter_datetime_picker/flutter_datetime_picker.dart';
import 'package:date_format/date_format.dart';

class DateTimePickerPage extends StatefulWidget {
    
    
  DateTimePickerPage({
    
    Key? key}) : super(key: key);

  @override
  _DateTimePickerPageState createState() => _DateTimePickerPageState();
}

class _DateTimePickerPageState extends State<DateTimePickerPage> {
    
    
  DateTime _nowDate = DateTime.now();
  DateTime _timeDate = DateTime.now();
  _showDatePicker() {
    
    
    DatePicker.showDatePicker(context,
        showTitleActions: true,
        //起始日期
        minTime: DateTime(2018, 3, 5),
        maxTime: DateTime(2022, 12, 31), onChanged: (date) {
    
    
      print('change $date');
    }, onConfirm: (date) {
    
    
      print('confirm $date');
      setState(() {
    
    
        _nowDate = date;
      });
    }, currentTime: DateTime.now(), locale: LocaleType.zh);
  }

  _showDateTimePicker() {
    
    
    DatePicker.showDateTimePicker(context,
        showTitleActions: true,
        minTime: DateTime(2020, 5, 5, 20, 50),
        maxTime: DateTime(2022, 12, 31, 05, 09), onChanged: (date) {
    
    
      print('change $date in time zone ' +
          date.timeZoneOffset.inHours.toString());
    }, onConfirm: (date) {
    
    
      print('confirm $date');
      setState(() {
    
    
        _timeDate = date;
      });
    }, locale: LocaleType.zh);
  }

  @override
  Widget build(BuildContext context) {
    
    
    return Scaffold(
      appBar: AppBar(
        title: Text("DatePicker"),
      ),
      body: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          InkWell(
            child: Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Text("${formatDate(_nowDate, [yyyy, '年', mm, '月', dd])}"),
                Icon(Icons.arrow_drop_down)
              ],
            ),
            onTap: _showDatePicker,
          ),
          SizedBox(height: 20),
          InkWell(
            child: Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Text("${formatDate(_timeDate, [yyyy,'-',mm,'-',dd," "HH,':',nn,':',ss])}"),
                Icon(Icons.arrow_drop_down)
              ],
            ),
            onTap: _showDateTimePicker,
          )
        ],
      ),
    );
  }
}

这里用到了时间选择组件的两种使用方式,一种是DatePicker(显示年月日),另一种是DateTimePicker(显示年月日时分)
在这里插入图片描述
在这里插入图片描述
更多使用方法可在官方文档例子中找出来修改

遇到的问题

/E:/Flutter/flutter/.pub-cache/hosted/pub.dartlang.org/flutter_datetime_picker-1.5.1/lib/flutter_datetime_picker.dart:311:32: Warning: Operand of null-aware
operation '??' has type 'Color' which excludes null.
 - 'Color' is from 'dart:ui'.
                  color: theme.backgroundColor ?? Colors.white,
                               ^

在这里插入图片描述
这个问题没有影响到我们的使用,报错是因为flutter版本更新而插件版本没有更新导致,我们可以在GitHub官方给的包上面修改,也可以找别人修改好后的地址再再本地下载,由于我对GitHub操作也不熟悉,就不再进行修改了,在B站TI营flutter教程第43讲有说到,地址https://www.bilibili.com/video/BV1S4411E7LY?p=43,可以自己学习。

猜你喜欢

转载自blog.csdn.net/m0_46527751/article/details/122609170
今日推荐