如何使用Dart格式化日期?

Set*_*add 91 dart

我有一个实例,DateTime我想将其格式化为String.我怎么做?我想把日期变成一个字符串,比如"2013-04-20".

Set*_*add 188

您可以使用intl包(安装程序)来设置日期格式.

对于en_US格式,它很简单:

import 'package:intl/intl.dart';

main() {
  var now = new DateTime.now();
  var formatter = new DateFormat('yyyy-MM-dd');
  String formatted = formatter.format(now);
  print(formatted); // something like 2013-04-20
}
Run Code Online (Sandbox Code Playgroud)

格式化有很多选项.来自文档:

 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
Run Code Online (Sandbox Code Playgroud)

对于非en_US日期,您需要显式加载语言环境.有关详细信息,请参阅https://www.dartdocs.org/documentation/intl/latest/intl/DateFormat-class.html.

  • 有没有办法在格式中添加毫秒? (3认同)
  • 需要pubspec.yaml中的依赖项:intl:^ 0.15.7 (2认同)

Sha*_*ank 25

如果有人想将字符串格式的日期转换为其他字符串格式,请先使用 DateTime.parse("2019-09-30") 然后将其传递给 DateFormat("date pattern").format() 像

dateFormate = DateFormat("dd-MM-yyyy").format(DateTime.parse("2019-09-30"));
Run Code Online (Sandbox Code Playgroud)

参考: Dart - 如何将 yyyy-MM-dd 中的简单日期字符串的格式更改为 dd-MM-yyyy


Per*_*ine 24

这也可以:

DateTime today = new DateTime.now();
String dateSlug ="${today.year.toString()}-${today.month.toString().padLeft(2,'0')}-${today.day.toString().padLeft(2,'0')}";
print(dateSlug);
Run Code Online (Sandbox Code Playgroud)

  • 不建议这样做,因为它未在用户区域设置中本地化。 (3认同)

Cíc*_*ura 18

另一种方法,使用intl包。

创建 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);
  }
}
Run Code Online (Sandbox Code Playgroud)

将此文件导入到您要使用 DateTime 类型的位置,您可以像这样使用它:

DateTime.now().format();

DateTime.now().format('MM/yyyy');

DateTime.now().format('MM/yyyy', 'es');
Run Code Online (Sandbox Code Playgroud)


liv*_*ove 15

pubspec.yaml:

dependencies:
  intl:
Run Code Online (Sandbox Code Playgroud)

主要.dart:

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
}
Run Code Online (Sandbox Code Playgroud)

结果:

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
Run Code Online (Sandbox Code Playgroud)


Pur*_*mar 12

如果您不想添加另一个库,也可以使用此方法

  DateTime dateTime = DateTime.now();
  String YYYY_MM_DD = dateTime.toIso8601String().split('T').first;
  print(YYYY_MM_DD); //2020-11-23

Run Code Online (Sandbox Code Playgroud)


小智 11


main() {
  final String pattern = 'yyyy-MM-dd';
  final String formatted = DateFormat(pattern).format(DateTime.now());
  print(formatted);
}
Run Code Online (Sandbox Code Playgroud)

更改yyyy-MM-dd字符串可以更改日期格式。我制作了用于玩这个模式字符串的应用程序。

您可以在我的应用程序中试验格式字符串,它是用 flutter 制作的。 https://biplobsd.github.io/EpochConverterApp

在这里您可以看到如何编辑图案以及显示在顶部的效果


小智 7

这给你一个社交网络中的日期:["今天","昨天","dayoftheweek"等.]

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 "thurdsday";
          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}';
      }
      return "";
    }
Run Code Online (Sandbox Code Playgroud)

  • 非常有用 - 谢谢。如果您要传递有时间的日期,请在方法顶部添加此附加行,否则“昨天”可能不起作用: tm = DateTime(tm.year, tm.month, tm.day); (3认同)

Rod*_*vis 7

您还可以指定日期格式,如前所述:https : //pub.dartlang.org/documentation/intl/latest/intl/DateFormat-class.html

import 'package:intl/intl.dart';
String formatDate(DateTime date) => new DateFormat("MMMM d").format(date);
Run Code Online (Sandbox Code Playgroud)

产生: March 4


Rav*_*ani 7

您可以使用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
}
Run Code Online (Sandbox Code Playgroud)

或者您可以使用date_format包在 flutter 中格式化日期。

import 'package:date_format/date_format.dart';

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

//02-03-2021
Run Code Online (Sandbox Code Playgroud)


小智 7

设置您的项目国际

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);
}
Run Code Online (Sandbox Code Playgroud)


Ani*_*mar 6

/// 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();
} 
Run Code Online (Sandbox Code Playgroud)


And*_*rey 5

有一个包date_format

dependencies:
    date_format: ^1.0.6
Run Code Online (Sandbox Code Playgroud)

import 'package:date_format/date_format.dart';

final formattedStr = formatDate(
    yourDateTime, [dd, '.', mm, '.', yy, ' ', HH, ':', nn]);

// output example "29.03.19 07:00"
Run Code Online (Sandbox Code Playgroud)

注意:分钟是nn

链接到包裹