formatDateTime static method

String formatDateTime({
  1. required bool timeSwitch,
  2. required bool dateSwitch,
})

Formats the current date/time into a string.

  • When dateSwitch is true, includes the date part in yyyy/MM/dd.
  • When timeSwitch is true, includes the time part in HH:mm:ss.
  • When both are true, they are separated by a single space.
  • When both are false, returns an empty string.

Returns the formatted string based on the selected parts.

Implementation

static String formatDateTime({
  required bool timeSwitch,
  required bool dateSwitch,
}) {
  if (!timeSwitch && !dateSwitch) return '';
  final now = DateTime.now();
  final buffer = StringBuffer();

  if (dateSwitch) {
    buffer
      ..write(now.year)
      ..write('/')
      ..write(_two(now.month))
      ..write('/')
      ..write(_two(now.day));
  }
  if (timeSwitch) {
    if (dateSwitch) buffer.write(' ');
    buffer
      ..write(_two(now.hour))
      ..write(':')
      ..write(_two(now.minute))
      ..write(':')
      ..write(_two(now.second));
  }
  return buffer.toString();
}