1

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?

jamesdlin
  • 81,374
  • 13
  • 159
  • 204

2 Answers2

1

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')),
);

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
jamesdlin
  • 81,374
  • 13
  • 159
  • 204
0

First, you can use a regex to parse the text:

RegExp exp = new RegExp(r"\d{2}");

The regex \d{2} matches every two digits of the string. Then you can make a list to store this group of digits:

Iterable<Match> matches = exp.allMatches('11082020_150258');
var list = matches.map((m) => m.group(0)).toList();

Getting the date part of the string:

String dateStr = list.sublist(0, 3).join('/') + list[3].toString();

Getting the time part of the string:

String timeStr = list.sublist(4).join(':');

Creating a DateTime object from the string (using DateFormat from intl package)

var parsedDate = DateFormat('dd/M/yyyy HH:mm:ss').parse(dateStr + ' ' + timeStr);

You can use this DateTime. If you want to print it in the format mentioned in the question (i.e., 11 August 2020, 3:02 PM):

DateFormat format = new DateFormat('d MMMM yyyy, HH:mm a', 'en_US');
print(format.format(parsedDate));

Full code:

RegExp exp = new RegExp(r"\d{2}");
Iterable<Match> matches =
exp.allMatches('11082020_150258');
var list =
matches.map((m) => m.group(0)).toList();
String dateStr =
    list.sublist(0, 3).join('/') + list[3].toString();
String timeStr = list.sublist(4).join(':');
var parsedDate = DateFormat('dd/M/yyyy HH:mm:ss')
    .parse(dateStr + ' ' + timeStr);
DateFormat format =
new DateFormat('d MMMM yyyy, HH:mm a', 'en_US');
print(format.format(parsedDate));
Mobina
  • 6,369
  • 2
  • 25
  • 41