且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Dart函数,用于格式化日期和时间

更新时间:2023-11-10 10:33:34

首先,您需要将字符串解析为 DateTime 对象。不幸的是, DateFormat 来自 package:intl 不支持没有字段分隔符的时间戳解析,因此您需要手动对其进行解析。您可以使用正则表达式:

You first will need to parse your string into a DateTime object. Unfortunately, DateFormat from package:intl does not support parsing timestamps without field separators, so you'll need to parse it manually. You can use a regular expression:

var timestampString = '11082020_150258';
var re = RegExp(
  r'^'
  r'(?<day>\d{2})'
  r'(?<month>\d{2})'
  r'(?<year>\d{4})'
  r'_'
  r'(?<hour>\d{2})'
  r'(?<minute>\d{2})'
  r'(?<second>\d{2})'
  r'$',
);

var match = re.firstMatch(timestampString);
if (match == null) {
  throw FormatException('Unrecognized timestamp format');
}
var dateTime = DateTime(
  int.parse(match.namedGroup('year')),
  int.parse(match.namedGroup('month')),
  int.parse(match.namedGroup('day')),
  int.parse(match.namedGroup('hour')),
  int.parse(match.namedGroup('minute')),
  int.parse(match.namedGroup('second')),
);

一旦有了 DateTime 对象,就可以使用 DateFormat 对其进行格式化:

Once you have a DateTime object, you can use DateFormat to format it:

var dateString = DateFormat('d MMMM yyyy').format(dateTime);
var timeString = DateFormat('h:mm a').format(dateTime);

print(dateString); // Prints: 11 August 2020
print(timeString); // Prints: 3:02 PM