Dart函数,用于格式化日期和时间 [英] Dart Function for Formatting Date and Time

查看:1946
本文介绍了Dart函数,用于格式化日期和时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何创建将'11082020_150258'之类的日期和时间转换为'2020年8月11日''3:02 PM'使用Dart吗?

How do you create a function to convert something like '11082020_150258' to Date and time like '11 August 2020' and '3:02 PM' using Dart?

推荐答案

首先,您需要将字符串解析为 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

这篇关于Dart函数,用于格式化日期和时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆