如何使用Dart格式化日期?

时间:2013-04-21 00:06:12

标签: dart

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

18 个答案:

答案 0 :(得分:131)

您可以使用intl包(installer)格式化日期。

对于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
}

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

 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日期,您需要显式加载语言环境。有关详细信息,请参阅https://www.dartdocs.org/documentation/intl/latest/intl/DateFormat-class.html

答案 1 :(得分:20)

这也可以:

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

答案 2 :(得分:7)

这给了您类似社交网络中的日期:[“今天”,“昨天”,“星期几”等。]

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

答案 3 :(得分:6)

您可以使用 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

答案 4 :(得分:6)

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

答案 5 :(得分:5)

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

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

参考: Dart - How to change format of simple date string which is in yyyy-MM-dd to dd-MM-yyyy

答案 6 :(得分:5)

如果您不想添加其他库,也可以使用此方法

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

答案 7 :(得分:4)

您还可以指定日期格式,如前所述: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);

产生:March 4

答案 8 :(得分:3)

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

答案 9 :(得分:2)

处理从字符串到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;
    }

答案 10 :(得分:2)

有一个包date_format

dependencies:
    date_format: ^1.0.6

代码

import 'package:date_format/date_format.dart';

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

// output example "29.03.19 07:00"

注意:分钟为 nn

link to the package

答案 11 :(得分:1)

如果您要将几种日期格式组合为一种,那么我们可以使用intl来做到这一点。

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

答案 12 :(得分:1)

另一种方式。

创建 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(pattern: 'MM/yyyy');

DateTime.now().format(pattern: 'MM/yyyy', locale: 'es');

答案 13 :(得分: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 Documentation

答案 14 :(得分:0)

String formatDate(String date) {
    return date.substring(0, 10).split('-').reversed.join().replaceAll('-', '/');
    
  }

采用“ yyyy-mm-dd H:i:s”格式

答案 15 :(得分:0)

17 ?- find3(_Kids), maplist(writeln, _Kids).
[first_name-angela,age-5,last_name-Leung,gender-female|_G5742]
[first_name-mary,age-7,last_name-Diamond,gender-female|_G5751]
[first_name-david,age-8,last_name-Grant,gender-male|_G5760]
true .

答案 16 :(得分:0)

您也可以使用此功能。

String getFormattedTime(int totalSeconds) {

    if (totalSeconds < 0) {
      return "00:00:00";
    }

    int remainingHours = (totalSeconds / 3600).floor();
    int remainingMinutes = (totalSeconds / 60).floor() - remainingHours * 60;
    int remainingSeconds = totalSeconds - remainingMinutes * 60 - remainingHours * 3600;

    return remainingHours.toString().padLeft(2, '0') +
        ":" +
        remainingMinutes.toString().padLeft(2, '0') +
        ":" +
        remainingSeconds.toString().padLeft(2, '0');
  }

输入:3600(以秒为单位)

输出:01:00:00

padLeft(2, '0')

已用于格式化最终字符串(即添加结尾的零)。

答案 17 :(得分:-1)

更简单的方法:

new DateFormat("dd-MM-y").format(YOUR_DATETIME_HERE)