我有一个DateTime的实例,我想将其格式化为字符串。我怎么做呢?我想把日期转换成一个字符串,类似于“2013-04-20”。
当前回答
您还可以像前面所述的那样指定日期格式:https://pub.dev/documentation/intl/latest/intl/DateFormat-class.html
import 'package:intl/intl.dart';
String formatDate(DateTime date) => new DateFormat("MMMM d").format(date);
出品时间:3月4日
其他回答
设置你的项目intl包
dateTimeFormet (date){
//MM-dd-yyyy
//yyyy-MM-dd
return DateFormat('dd-MM-yyyy').format(date);// you can set your formet
}
void main (){
var date = 01-11-2022 00 : 00
var _datetime = dateTimeFormet(date);
print(_dateTime);
}
如果你想将多个日期格式合并为一个,这就是我们使用intl的方法。
DateFormat('yMMMd').addPattern(DateFormat.HOUR24_MINUTE).format(yourDateTime))
有一个包date_format
dependencies:
date_format:
code
import 'package:date_format/date_format.dart';
final formattedStr = formatDate(
yourDateTime, [dd, '.', mm, '.', yy, ' ', HH, ':', nn]);
// output example "29.03.19 07:00"
注意:分钟是nn
链接到软件包
无依赖项方法[用于将日期显示为格式化字符串]
如果你想要以日/月/年的形式显示你的DateTime值或任何你喜欢的格式,字符串插值可以很方便:
"${_date.day} / ${_date.month} / ${_date.year}"
示例输出:
It's 23 out of 4 out of 1920
我不想使用任何额外的库,所以我走了这条路。
/// Get date as a string for display.
String getFormattedDate(String date) {
/// Convert into local date format.
var localDate = DateTime.parse(date).toLocal();
/// inputFormat - format getting from api or other func.
/// e.g If 2021-05-27 9:34:12.781341 then format must be yyyy-MM-dd HH:mm
/// If 27/05/2021 9:34:12.781341 then format must be dd/MM/yyyy HH:mm
var inputFormat = DateFormat('yyyy-MM-dd HH:mm');
var inputDate = inputFormat.parse(localDate.toString());
/// outputFormat - convert into format you want to show.
var outputFormat = DateFormat('dd/MM/yyyy HH:mm');
var outputDate = outputFormat.format(inputDate);
return outputDate.toString();
}
推荐文章
- 错误地使用父数据小部件。扩展小部件必须放置在flex小部件中
- 颤振给容器圆形边界
- Flutter: RenderBox没有布局
- 颤振插件未安装错误;当运行'扑动医生'时
- 我如何“休眠”Dart程序
- 在Flutter app上检查是否有网络连接
- Flutter and google_sign_in plugin: PlatformException(sign_in_failed, com.google.android.gms.common.api.ApiException: 10:, null)
- 如何在扑动中格式化日期时间
- 在Flutter中Column的子元素之间的空间
- Visual Studio代码- URI的目标不存在" package:flutter/material.dart "
- 如何检查Flutter应用程序是否正在调试中运行?
- 在Flutter中向有状态小部件传递数据
- 未处理异常:ServicesBinding.defaultBinaryMessenger在绑定初始化之前被访问
- 颤振-换行文本
- 如何在Dart中四舍五入到小数点后的给定精度程度?