一 日期获取与转换
可以使用第三方库 进行格式转换 https://pub.dev/packages/date_format/example
var now = DateTime.now();
// 打印结果 2023-02-19 08:43:41.258019
print(now);
// 打印时间戳 1676767470599
print(now.millisecondsSinceEpoch);
// 将时间戳转换为时间
print(DateTime.fromMillisecondsSinceEpoch(1676767470599));
// 利用第三方日期的格式转换 date_format
print(formatDate(DateTime.now(), [yyyy, '年', mm, '月', dd, '日']));
二 系统的日期组件
import 'package:flutter/material.dart';
import 'package:date_format/date_format.dart';
class DatePickerPage extends StatefulWidget {
const DatePickerPage({super.key});
@override
State<DatePickerPage> createState() => _DatePickerPageState();
}
class _DatePickerPageState extends State<DatePickerPage> {
var _datetime = DateTime.now();
var _time = TimeOfDay(hour: 11, minute: 31);
// 日期组件
_showDatePicker() async {
var date = await showDatePicker(
context: context,
initialDate: _datetime,
firstDate: DateTime(2020),
lastDate: DateTime(2025));
if (date == null) return;
setState(() {
_datetime = date;
});
}
// 时间组件
_showTimePicker() async {
var time = await showTimePicker(context: context, initialTime: _time);
if (time == null) return;
print(time);
setState(() {
this._time = time;
});
}
@override
void initState() {
super.initState();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text("DatePicker")),
body: Center(
child: InkWell(
onTap: () {
// 选择日期组件
_showDatePicker();
// _showTimePicker();
},
child: Row(
children: [
Text(formatDate(_datetime, [yyyy, '年', mm, '月', dd, '日'])),
Icon(Icons.arrow_drop_down),
],
),
)),
);
}
}
![](https://i-blog.csdnimg.cn/blog_migrate/1f7a94e06672e53c9c223b14f9d7cf0d.png)
![](https://i-blog.csdnimg.cn/blog_migrate/673e2dafd5d2b50c10e164aad162e460.png)
日期组件的本地化
http://bbs.itying.com/topic/5cfb2a12f322340b2c90e764