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


当前回答


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

在这里你可以看到我如何编辑模式和这个效果显示在顶部

其他回答

可以使用intl包格式化flutter中的日期。

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包来格式化flutter中的日期。

import 'package:date_format/date_format.dart';

final formattedStr = formatDate(DateTime.now(), [dd, '-', mm, '-', yyyy]);

//02-03-2021

设置你的项目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日

目前天:

DateTime.now().day, //something like 26

目前月:

DateTime.now().month, //something like 4

本年度:

DateTime.now().year, //something like 2022

目前Houre:

DateTime.now().hour, //something like 12

当前时间:

DateTime.now().minute, //something like 13

目前第二:

DateTime.now().second, //something like 44
/// 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();
}