Skip to main content

general_date_format 2.0.0 copy "general_date_format: ^2.0.0" to clipboard
general_date_format: ^2.0.0 copied to clipboard

A Dart/Flutter package to format dates in a flexible and generalized way, extending the functionality of the general_datetime package for versatile date formatting.

example/lib/main.dart

import 'package:flutter/material.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
import 'package:general_date_format/general_date_format.dart';
import 'package:intl/intl.dart' as intl;
import 'package:general_datetime/delegates.dart';
import 'package:general_datetime/general_datetime.dart';

void main() => runApp(const MyApp());

class MyApp extends StatelessWidget {
  const MyApp({super.key, this.now});

  /// Optional native clock, sampled once when the example screen is created.
  /// Omit this to use the current local time; tests can supply a frozen clock.
  final DateTime Function()? now;

  @override
  Widget build(BuildContext context) => MaterialApp(
        title: 'General Date Format',
        theme: ThemeData(colorSchemeSeed: Colors.indigo),
        localizationsDelegates: GlobalMaterialLocalizations.delegates,
        supportedLocales: const [Locale('en'), Locale('fa'), Locale('ar')],
        home: FormatExample(now: now),
      );
}

class FormatExample extends StatefulWidget {
  const FormatExample({super.key, this.now});

  /// Clock for the screen's initial snapshot; rebuilds retain that snapshot.
  final DateTime Function()? now;

  @override
  State<FormatExample> createState() => _FormatExampleState();
}

class _FormatExampleState extends State<FormatExample> {
  String locale = 'en';
  late final Map<String, DateTime> _dates;

  @override
  void initState() {
    super.initState();
    final instant = (widget.now ?? DateTime.now)();
    _dates = {
      'Gregorian': instant,
      'Persian': PersianDateTime.fromDateTime(instant),
      'Hijri': HijriDateTime.fromDateTime(instant),
    };
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('General Date Format')),
      body: ListView(
        padding: const EdgeInsets.all(16),
        children: [
          const Text(
              'The input date selects the calendar. The locale selects language and digits.'),
          DropdownButton<String>(
            value: locale,
            items: const [
              DropdownMenuItem(value: 'en', child: Text('English')),
              DropdownMenuItem(value: 'fa', child: Text('Persian')),
              DropdownMenuItem(value: 'ar', child: Text('Arabic')),
            ],
            onChanged: (value) => setState(() => locale = value!),
          ),
          for (final entry in _dates.entries)
            _calendarCard(entry.key, entry.value),
        ],
      ),
    );
  }

  Widget _calendarCard(String name, DateTime date) {
    final isCalendar = date is PersianDateTime || date is HijriDateTime;
    // The app chooses intl and lets Flutter's delegate initialize its data.
    final gregorian = intl.DateFormat('yyyy/MM/dd', locale);
    final numeric = GeneralDateFormat('yyyy/MM/dd', locale);
    final input = isCalendar ? numeric.format(date) : gregorian.format(date);
    final parsed = isCalendar
        ? numeric.parseStrict(input, date, true)
        : gregorian.parseStrict(input, true);
    final full = isCalendar
        ? GeneralDateFormat.yMMMMEEEEd(locale).add_Hm().format(date)
        : intl.DateFormat.yMMMMEEEEd(locale).add_Hm().format(date);
    return Card(
      child: Padding(
        padding: const EdgeInsets.all(16),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text(name, style: Theme.of(context).textTheme.titleLarge),
            const SizedBox(height: 8),
            SelectableText(full),
            SelectableText(input),
            const SizedBox(height: 8),
            Text('Parsed in UTC: ${parsed.isUtc}'),
            Text(
                'Calendar fields: ${parsed.year}/${parsed.month}/${parsed.day}'),
            if (date is PersianDateTime || date is HijriDateTime)
              TextButton.icon(
                key: ValueKey('pick-$name'),
                onPressed: () => _pickDate(name, date),
                icon: const Icon(Icons.calendar_month),
                label: Text('Choose $name date'),
              ),
          ],
        ),
      ),
    );
  }

  Future<void> _pickDate(String name, DateTime initial) async {
    final persian = initial is PersianDateTime;
    final CalendarDelegate<DateTime> calendarDelegate = persian
        ? const PersianCalendarDelegate()
        : const HijriCalendarDelegate();
    final materialDelegate = persian
        ? PersianCalendarMaterialLocalizations.delegate
        : HijriCalendarMaterialLocalizations.delegate;
    final firstDate = persian
        ? PersianDateTime(initial.year - 2)
        : HijriDateTime(initial.year - 2);
    final lastDate = persian
        ? PersianDateTime(initial.year + 2, 12, 29)
        : HijriDateTime(initial.year + 2, 12, 29);
    final selected = await showDatePicker(
      context: context,
      initialDate: initial,
      firstDate: firstDate,
      lastDate: lastDate,
      currentDate: initial,
      calendarDelegate: calendarDelegate,
      builder: (context, child) => Localizations.override(
        context: context,
        locale: Locale(locale),
        delegates: [materialDelegate],
        child: child!,
      ),
    );
    if (!mounted || selected == null) return;
    ScaffoldMessenger.of(context).showSnackBar(SnackBar(
      content: Text(
          'Selected $name: ${GeneralDateFormat.yMd(locale).format(selected)}'),
    ));
  }
}
2
likes
160
points
246
downloads

Documentation

Documentation
API reference

Publisher

unverified uploader

Weekly Downloads

A Dart/Flutter package to format dates in a flexible and generalized way, extending the functionality of the general_datetime package for versatile date formatting.

Homepage
Repository (GitHub)
View/report issues

Topics

#date #time #format #utils #service

License

BSD-3-Clause (license)

Dependencies

flutter, flutter_localizations, general_date_format_core, general_datetime

More

Packages that depend on general_date_format