如何使用Dart格式化日期?


141

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

Answers:


298

您可以使用该intl软件包(安装程序)格式化日期。

对于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如果您想更深入地了解,则其中包含每种国家/地区/语言的所有格式。


国际机场坏了吗?未捕获的错误:FileSystemException:无法打开文件,路径= 'E:\镖\ WS \网络\包\国际\ intl.dart'(OS错误:系统找不到指定的路径。
javapadawan

1
有什么办法可以将毫秒添加到格式中?
Kaspi

2
需要pubspec.yaml中的依赖项:intl:^ 0.15.7
murt

我们如何只取一个月。1月1日,2月2日...?我已经尝试过DateFormat('MM')。format(DateTime.now()); 但无法正常工作。请分享您的建议。
Kamlesh

@Kaspi尝试以“ S”表示小数秒
badelectron77

31

这也将起作用:

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


13

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

dateFormate = DateFormat("dd-MM-yyyy").format(DateTime.parse("2019-09-30"));

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


1
您的代码使用DateFormat但您的文本说DateTime.format()
mFeinstein

糟糕!一个大失误。已更改:)
Shashank

11

这样,您就可以在社交网络中找到日期:[“今天”,“昨天”,“星期几”等。

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}';
      }
    }

1
非常有用-谢谢。如果要传递的日期中带有时间,则在方法顶部添加此额外的行,否则'昨天'可能不起作用:tm = DateTime(tm.year,tm.month,tm.day);
尼克·赖特

8

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

链接到包裹


2

pubspec.yaml:

dependencies:
  intl:

main.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
}

结果:

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

1

如果您要将几种日期格式组合为一种,这就是我们可以使用的方式intl

DateFormat('yMMMd').addPattern(DateFormat.HOUR24_MINUTE).format(yourDateTime))

0
import 'package:intl/intl.dart';

main() {
  var formattedDate = new DateTime.Format('yyyy-MM-dd').DateTime.now();
  print(formattedDate); // something like 2020-04-16
}

有关更多详细信息,请参阅DateFormat文档。


0

处理年度季度,从字符串到DateTime,我没有找到合适的解决方案,所以这样做:

    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;
    }
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.