Date and time stamp
You can use datetime to get the current date from the fluent Now(). now.millisecondsSinceEpoch can get the timestamp
What is a timestamp
"Timestamp" refers to the total number of seconds from 00:00:00 GMT on January 1, 1970 (08:00:00 GMT on January 1, 1970) to now. Generally speaking, timestamp is a complete and verifiable data that can indicate that a data already exists at a specific time point.
Generally speaking, it means that the time format is converted into a format that is convenient for communication and storage. For example, 2020-08-15 15:07:17 is converted into a timestamp (MS) 1597475237894 < - it is the converted format
Date to timestamp:
var now = new DateTime.now(); print(now.millisecondsSinceEpoch);//Unit: ms, 13 bit time
Timestamp to date:
var now = new DateTime.now(); var a=now.millisecondsSinceEpoch; //time stamp 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("Get current time"), onPressed: () { print("The current time is: $now"); print("The timestamp is: ${now.millisecondsSinceEpoch}"); print( DateTime.fromMillisecondsSinceEpoch(1642681440235)); }, ), ); } }
Convert to mm / DD / yy format
From the above results, we can see that datetime The result printed by now() is
2022-01-20 12:24:00.235260 if we want to convert it to the form of year, month and day, we can use the third-party library. The import of third-party libraries has been studied in Dart's previous study. You can refer to it This article , the libraries we use can be found here https://pub.dev/packages/date_format/install
First, set date_format: ^2.0.5 copy to our project's pubspec Yaml file
After copying, click ctrl+s to save. The output will automatically execute the shuttle pub get command to download (if not executed, manually enter the execution). When in use, you can import the package into the corresponding file.
use:
print(formatDate(DateTime.now(), [yyyy, 'year', mm, 'month', dd]));
The complete code will not be put here, and the output result is:
I/flutter (16489): Current time: 2022-01-20 12:24:00.235260 I/flutter (16489): Timestamp: 164268144235 I/flutter (16489): 2022 January 20 //This is the result of the above code execution
Use the built-in date and time component
// 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, 'year', mm, 'month', 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, ) ], ) ], ), ); } }
Need attention
- InkWell is suitable for setting the event callback of non button components. We can regard it as a button and use onTap internally to set the callback event
- The main methods are as follows: one is to set the date (month, year, day) and the other is to set the time (time). Here, two methods are used to obtain the date (time) we choose. The other is through Then, the other is to modify the method with async through asynchrony, and then obtain the value internally through 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!; }); }
Time selection component displays Chinese
It can be seen from the above figure that the time selection component is in English and we want to change it to Chinese
Refer to TI camp's article http://bbs.itying.com/topic/5cfb2a12f322340b2c90e764
- The first is in pubspec Introduced into yaml
flutter_localizations: sdk: flutter
- Import internationalized package Fluent_ localizations
import 'package:flutter_localizations/flutter_localizations.dart';
- Add in main
import 'package:flutter_localizations/flutter_localizations.dart'; void main() => runApp(MyApp()); class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( localizationsDelegates: [ //here GlobalMaterialLocalizations.delegate, GlobalWidgetsLocalizations.delegate, ], supportedLocales: [ //here const Locale('zh', 'CH'), const Locale('en', 'US'), ], locale: const Locale("zh"), home:DatePickerDemo(), onGenerateRoute: onGenerateRoute, ); } }
After Sinicization:
Third party time component
Address of the third-party library used https://pub.dev/packages/flutter_datetime_picker/install
Before use, or in pubspec Import in yaml
dependencies: flutter_datetime_picker: ^1.5.1
Add statement on import
import 'package:flutter_datetime_picker/flutter_datetime_picker.dart';
use
// 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, //Start date 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, 'year', mm, 'month', 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, //Start date 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, 'year', mm, 'month', 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, ) ], ), ); } }
There are two ways to use the time selection component, one is DatePicker (display year, month and day), and the other is DateTimePicker (display year, month, day and time)
More usage methods can be found and modified in the example of official documents
Problems encountered
/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, ^
This problem does not affect our use. The error is due to the updated version of the flutter but not the updated version of the plug-in. We can modify it on the package officially given by GitHub, or find someone else's modified address and download it locally. Since I am not familiar with the operation of GitHub, I will not modify it any more. It is mentioned in Chapter 43 of the flutter tutorial of TI camp at station B https://www.bilibili.com/video/BV1S4411E7LY?p=43 , you can learn by yourself.