d4_time_format library
Parse and format times, inspired by strptime and strftime.
This package provides an approximate Dart implementation of the
venerable
strptime
and
strftime
functions from the C standard library, and can be used to parse or format
dates in a variety of locale-specific representations. To format a date,
create a formatter (see TimeFormatLocale.format) from a specifier (a
string with the desired format directives, indicated by %
); then pass a
date to the formatter, which returns a string. For example, to convert the
current date to a human-readable string:
final formatTime = timeFormat("%B %d, %Y");
formatTime(DateTime.timestamp()); // "May 31, 2023"
Likewise, to convert a string back to a date, create a parser:
final parseTime = timeParse("%B %d, %Y", isUtc: true);
parseTime("June 30, 2015"); // 2023-05-31
You can implement more elaborate conditional time formats, too. For example, here’s a multi-scale time format using time intervals:
final formatMillisecond = timeFormat(".%L"),
formatSecond = timeFormat(":%S"),
formatMinute = timeFormat("%I:%M"),
formatHour = timeFormat("%I %p"),
formatDay = timeFormat("%a %d"),
formatWeek = timeFormat("%b %d"),
formatMonth = timeFormat("%B"),
formatYear = timeFormat("%Y");
multiFormat(DateTime date) {
return (timeSecond(date).isBefore(date)
? formatMillisecond
: timeMinute(date).isBefore(date)
? formatSecond
: timeHour(date).isBefore(date)
? formatMinute
: timeDay(date).isBefore(date)
? formatHour
: timeMonth(date).isBefore(date)
? (timeWeek(date).isBefore(date)
? formatDay
: formatWeek)
: timeYear(date).isBefore(date)
? formatMonth
: formatYear)(date);
}
This package is used by D4 time scales to generate human-readable ticks.
Classes
- TimeFormatLocale
- Time locale formats define how a date should be parsed and formatted in a locale-specific way.
Functions
-
timeFormat(
String specifier) → String Function(DateTime) - An alias for TimeFormatLocale.format on the default locale.
-
timeFormatDefaultLocale(
{required String dateTime, required String date, required String time, required List< String> periods, required List<String> days, required List<String> shortDays, required List<String> months, required List<String> shortMonths}) → TimeFormatLocale - Equivalent to TimeFormatLocale.new, except it also redefines timeFormat and timeParse to the new locale’s TimeFormatLocale.format and TimeFormatLocale.parse.
-
timeFormatDefaultLocaleFromJson(
Map< String, dynamic> definition) → TimeFormatLocale -
Equivalent to timeFormatDefaultLocale, but it accepts a JSON
definition
object instead of individual arguments -
timeParse(
String specifier, {bool isUtc = false}) → DateTime? Function(String) - An alias for TimeFormatLocale.parse on the default locale.