Flutter 获取日期
DateTime d = DeteTime.now();
d.yaear /*年*/
d.month /*月*/
d.day /*日*/
d.hour /*时*/
d.minuter /*分*/
d.second /*秒*/
获取时间戳
DateTime d = DateTime.now();
d.millisecondsSinceEpoch
日期转之间戳
DateTime d=DateTime(2023,08,1);
print(d.millisecondsSinceEpoch);
提示
在 Dart 中转换时间戳系统转换的时毫秒级,部分 SDK 的时间戳为 秒级需要做下计算
DateTime d=DateTime(2023,08,1);
print(d.millisecondsSinceEpoch ~/ 1000);
字符串转时间
DateTime d=DateTime.parse("2021-08-01 08:01:30");
print(d.millisecondsSinceEpoch);
时间戳转日期
DateTime d = DateTime(2023, 08, 1);
int unixtime = d.millisecondsSinceEpoch;
print(DateTime.fromMillisecondsSinceEpoch(unixtime));
时间加减
DateTime time = DateTime.now();
print(time);
print(time.add(const Duration(minutes: 30)));
print(time.add(const Duration(minutes: -30)))
弹出日期选择器
DateTime? time = await showDatePicker(
context:context,
initialDate:当前时间,
firsDate:DateTime(1990), /*最早时期*/
lastData:DateTime(2060), /* 最晚时期*/
)
if(time != null){
print(time)
}
弹出时间选择器
TimeOfDay? time = await showTimePicker(
context:context,
initialTime:_time, /* 当前时间 */
)
if(time != null){
print(time)
}
时间戳自定义格式化日期
安装
intl: ^0.18.1
使用
DateTime dateTime = DateTime.fromMillisecondsSinceEpoch(timestamp * 1000); /*将秒转换为毫秒 */
DateTime localDateTime = dateTime.toLocal();
String formattedDate = DateFormat('yyyy-MM-dd').format(localDateTime);
国际化 flutter_localizations
第三方组件
配置 pubspec.yaml
dependencies:
flutter:
sdk: flutter
flutter_localizations:
sdk: flutter
配置根组件
import 'package:flutter_localizations/flutter_localizations.dart';
MaterialApp(
localizationsDelegates: const [
/*此处*/
GlobalMaterialLocalizations.delegate,
GlobalWidgetsLocalizations.delegate,
],
supportedLocales: const[
/*此处*/
Locale('zh', 'CH'),
Locale('en', 'US'),
],
)
在组件中使用
showDatePicker() async{
var date =await showDatePicker(
context: context,
initialDate: _datetime,
firstDate:DateTime(1900),
lastDate:DateTime(2050),
locale: Locale('zh'),
);
if(date==null) return;
print(date);
setState(() {
_datetime=date;
});
}