我有一个实例,DateTime
我想将其格式化为字符串。我怎么做?我想把日期变成一个字符串,比如“2013-04-20”。
21 回答
对于en_US
格式,这很简单:
import 'package:intl/intl.dart';
main() {
final DateTime now = DateTime.now();
final DateFormat formatter = DateFormat('yyyy-MM-dd');
final String formatted = formatter.format(now);
print(formatted); // something like 2013-04-20
}
有许多格式化选项。从文档:
ICU Name Skeleton
-------- --------
DAY d
ABBR_WEEKDAY E
WEEKDAY EEEE
ABBR_STANDALONE_MONTH LLL
STANDALONE_MONTH LLLL
NUM_MONTH M
NUM_MONTH_DAY Md
NUM_MONTH_WEEKDAY_DAY MEd
ABBR_MONTH MMM
ABBR_MONTH_DAY MMMd
ABBR_MONTH_WEEKDAY_DAY MMMEd
MONTH MMMM
MONTH_DAY MMMMd
MONTH_WEEKDAY_DAY MMMMEEEEd
ABBR_QUARTER QQQ
QUARTER QQQQ
YEAR y
YEAR_NUM_MONTH yM
YEAR_NUM_MONTH_DAY yMd
YEAR_NUM_MONTH_WEEKDAY_DAY yMEd
YEAR_ABBR_MONTH yMMM
YEAR_ABBR_MONTH_DAY yMMMd
YEAR_ABBR_MONTH_WEEKDAY_DAY yMMMEd
YEAR_MONTH yMMMM
YEAR_MONTH_DAY yMMMMd
YEAR_MONTH_WEEKDAY_DAY yMMMMEEEEd
YEAR_ABBR_QUARTER yQQQ
YEAR_QUARTER yQQQQ
HOUR24 H
HOUR24_MINUTE Hm
HOUR24_MINUTE_SECOND Hms
HOUR j
HOUR_MINUTE jm
HOUR_MINUTE_SECOND jms
HOUR_MINUTE_GENERIC_TZ jmv
HOUR_MINUTE_TZ jmz
HOUR_GENERIC_TZ jv
HOUR_TZ jz
MINUTE m
MINUTE_SECOND ms
SECOND s
对于非en_US
日期,您需要在语言环境中显式加载。有关更多信息,请参阅DateFormat
文档。包含每个国家/语言的date_symbol_data_local.dart
所有格式,如果您想要更深入的了解。
这也可以:
DateTime today = new DateTime.now();
String dateSlug ="${today.year.toString()}-${today.month.toString().padLeft(2,'0')}-${today.day.toString().padLeft(2,'0')}";
print(dateSlug);
您还可以指定日期格式,如前所述: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);
生产:March 4
如果有人想将字符串格式的日期转换为其他字符串格式,请先使用 DateTime.parse("2019-09-30") 然后将其传递给 DateFormat("date pattern").format()
dateFormate = DateFormat("dd-MM-yyyy").format(DateTime.parse("2019-09-30"));
pubspec.yaml:
dependencies:
intl:
主要飞镖:
import 'package:intl/intl.dart'; // for date format
import 'package:intl/date_symbol_data_local.dart'; // for other locales
void main() {
var now = DateTime.now();
print(DateFormat().format(now)); // This will return date using the default locale
print(DateFormat('yyyy-MM-dd hh:mm:ss').format(now));
print(DateFormat.yMMMMd().format(now)); // print long date
print(DateFormat.yMd().format(now)); // print short date
print(DateFormat.jms().format(now)); // print time
initializeDateFormatting('es'); // This will initialize Spanish locale
print(DateFormat.yMMMMd('es').format(now)); // print long date in Spanish format
print(DateFormat.yMd('es').format(now)); // print short date in Spanish format
print(DateFormat.jms('es').format(now)); // print time in Spanish format
}
结果:
May 31, 2020 5:41:42 PM
2020-05-31 05:41:42
May 31, 2020
5/31/2020
5:41:42 PM
31 de mayo de 2020
31/5/2020
17:41:42
如果您不想添加另一个库,也可以使用此方法
DateTime dateTime = DateTime.now();
String YYYY_MM_DD = dateTime.toIso8601String().split('T').first;
print(YYYY_MM_DD); //2020-11-23
这为您提供了社交网络中的日期:[“今天”、“昨天”、“星期几”等。]
void main() {
DateTime now = new DateTime(2018,6,26);
print(date(now));
}
String date(DateTime tm) {
DateTime today = new DateTime.now();
Duration oneDay = new Duration(days: 1);
Duration twoDay = new Duration(days: 2);
Duration oneWeek = new Duration(days: 7);
String month;
switch (tm.month) {
case 1:
month = "january";
break;
case 2:
month = "february";
break;
case 3:
month = "march";
break;
case 4:
month = "april";
break;
case 5:
month = "may";
break;
case 6:
month = "june";
break;
case 7:
month = "july";
break;
case 8:
month = "august";
break;
case 9:
month = "september";
break;
case 10:
month = "october";
break;
case 11:
month = "november";
break;
case 12:
month = "december";
break;
}
Duration difference = today.difference(tm);
if (difference.compareTo(oneDay) < 1) {
return "today";
} else if (difference.compareTo(twoDay) < 1) {
return "yesterday";
} else if (difference.compareTo(oneWeek) < 1) {
switch (tm.weekday) {
case 1:
return "monday";
case 2:
return "tuesday";
case 3:
return "wednesday";
case 4:
return "thursday";
case 5:
return "friday";
case 6:
return "saturday";
case 7:
return "sunday";
}
} else if (tm.year == today.year) {
return '${tm.day} $month';
} else {
return '${tm.day} $month ${tm.year}';
}
}
您可以使用intl包在颤振中格式化日期。
void main() {
final DateTime now = DateTime.now();
final DateFormat format = DateFormat('yyyy-MM-dd');
final String formatted = format.format(now);
// 2021-03-02
}
或者您可以使用date_format包在颤动中格式化日期。
import 'package:date_format/date_format.dart';
final formattedStr = formatDate(DateTime.now(), [dd, '-', mm, '-', yyyy]);
//02-03-2021
有一个包 date_format
dependencies:
date_format:
代码
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_time_extension.dart
import 'package:intl/date_symbol_data_local.dart';
import 'package:intl/intl.dart';
extension DateTimeExtension on DateTime {
String format([String pattern = 'dd/MM/yyyy', String? locale]) {
if (locale != null && locale.isNotEmpty) {
initializeDateFormatting(locale);
}
return DateFormat(pattern, locale).format(this);
}
}
将此文件导入您要使用 DateTime 类型的位置(您必须手动导入),您可以像这样使用它:
DateTime.now().format();
DateTime.now().format('MM/yyyy');
DateTime.now().format('MM/yyyy', 'es');
/// 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();
}
如果您想将多种日期格式合并为一种,我们可以使用intl
.
DateFormat('yMMMd').addPattern(DateFormat.HOUR24_MINUTE).format(yourDateTime))
处理从字符串到日期时间的年度季度,我没有找到合适的解决方案,所以做了这个:
List<String> dateAsList = 'Q1 2001'.split(' ');
DateTime dateTime = DateTime.now();
String quarter = dateAsList[0];
int year = int.parse(dateAsList[1]);
switch(quarter) {
case "Q1": dateTime = DateTime(year, 1);
break;
case "Q2": dateTime = DateTime(year, 4);
break;
case "Q3": dateTime = DateTime(year, 7);
break;
case "Q4": dateTime = DateTime(year, 10);
break;
}
无依赖方法 [将日期显示为格式化字符串]
如果您想将 DateTime 值显示为日/月/年或您喜欢的任何其他格式,字符串插值会很方便:
"${_date.day} / ${_date.month} / ${_date.year}"
样本输出:
23 / 4 / 1920
我不想使用任何额外的库,所以我就这样走了。
String dateConverter(String date) {
// Input date Format
final format = DateFormat("dd-MM-yyyy");
DateTime gettingDate = format.parse(date);
final DateFormat formatter = DateFormat('yyyy-MM-dd');
// Output Date Format
final String formatted = formatter.format(gettingDate);
return date;
}
String formatDate(String date) {
return date.substring(0, 10).split('-').reversed.join().replaceAll('-', '/');
}
从格式“yyyy-mm-dd H:i:s”
import 'package:intl/intl.dart';
main() {
var formattedDate = new DateTime.Format('yyyy-MM-dd').DateTime.now();
print(formattedDate); // something like 2020-04-16
}
更多细节可以参考DateFormat 文档
main() {
final String pattern = 'yyyy-MM-dd';
final String formatted = DateFormat(pattern).format(DateTime.now());
print(formatted);
}
更改yyyy-MM-dd
字符串可以更改日期格式。我用这个模式字符串制作了应用程序。
您可以在我的应用程序中试验格式字符串它是用颤振制作的。 https://biplobsd.github.io/EpochConverterApp
更简单的方法:
new DateFormat("dd-MM-y").format(YOUR_DATETIME_HERE)
使用“H:mm”查看完整的分钟数,例如 13:08 而不是 13:8
要获得一个包含日期和时间的用户友好型字符串,您可以使用以下命令:
import 'package:intl/intl.dart';
main() {
final DateTime someDateTime = DateTime(2017, 9, 7, 17, 30);
final DateFormat formatter = DateFormat.yMMMd().add_jms();
final String formatted = formatter.format(someDateTime);
print(formatted); // Sep 7, 2017 5:30:00 PM (in the US)
}