我有一个DateTime的实例,我想将其格式化为字符串。我怎么做呢?我想把日期转换成一个字符串,类似于“2013-04-20”。


当前回答

设置你的项目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);
}

其他回答

您还可以像前面所述的那样指定日期格式: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日

有一个包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

链接到软件包

/// 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();
} 

无依赖项方法[用于将日期显示为格式化字符串]

如果你想要以日/月/年的形式显示你的DateTime值或任何你喜欢的格式,字符串插值可以很方便:

"${_date.day} / ${_date.month} / ${_date.year}"

示例输出:

It's 23 out of 4 out of 1920

我不想使用任何额外的库,所以我走了这条路。

用“H:mm”来查看完整的分钟,比如13:08,而不是13:8