1. Flutter中的日期转换
// 初始化当前日期
DateTime _nowDate = DateTime.now();
// 获取当前时间
print(_nowDate);
// 2021-01-01 18:18:37.522021
// 获取当前时间戳
print(_nowDate.millisecondsSinceEpoch);
// 1609496743946
// 将时间戳转为格式化的时间
print(DateTime.fromMillisecondsSinceEpoch(1609496743946));
// 2021-01-01 18:25:43.946
2. 使用第三方插件进行日期转换
1. 安装 date_format 插件。
dependencies:
flutter:
sdk: flutter
date_format: ^1.0.6
pubspec.yaml中配置保存后,在VS Code环境中会自动下载依赖包。
如果无法正常下载,执行 flutter pub get。
2. 在需要使用插件的文件中引入安装包。
import 'package:date_format/date_format.dart';
3. 使用插件
// 初始化当前日期
DateTime _nowDate = DateTime.now();
print(formatDate(_nowDate, [yyyy,'年',mm,'月',dd]));
// 2021年01月01
print(formatDate(_nowDate,[yyyy,'年',mm,'月',dd,' ',HH,':',nn]))
// 2021年01月01 12:00