如何用Dart格式化日期?

您可以使用intl package来格式化日期。

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

Leave a Reply

邮箱地址不会被公开。 必填项已用*标注

You may use these HTML tags and attributes:

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>