Sample code for 30+ languages & platforms
Dart

Compute Difference Between Two DateTime Strings

Demonstrates how to compute the difference between two datetime strings.

Chilkat Dart Downloads

Dart
import 'package:chilkat/chilkat.dart';

void main() {
  // Imagine we have these strings:

  final t1 = '2022-11-14 15:45:38';
  final t2 = '2022-11-16 17:23:41';

  // How many minutes are between the two?

  // First, we'd want load each date/time into a Chilkat CkDateTime object.
  // In this case, there are no CkDateTime methods that accept the above format.
  // However.. the CkDateTime's SetFromTimestamp will accept a date in the format "YYYY-MM-DDThh:mm:ssZ"

  // First modify the above dates to the timestamp format.
  final sb1 = CkStringBuilder();
  sb1.append(t1);
  var count = sb1.replace(' ', 'T');
  sb1.append('Z');

  final sb2 = CkStringBuilder();
  sb2.append(t2);
  count = sb2.replace(' ', 'T');
  sb2.append('Z');

  // Load each into a CkDateTime
  final dt1 = CkDateTime();
  dt1.setFromTimestamp(sb1.getAsString());
  // verify...
  print(dt1.getAsTimestamp(false));

  final dt2 = CkDateTime();
  dt2.setFromTimestamp(sb2.getAsString());
  // verify...
  print(dt2.getAsTimestamp(false));

  // Get the difference in seconds
  final diffSeconds = dt2.diffSeconds(dt1);
  print('Difference in seconds: $diffSeconds');
  print('Difference in minutes: ${diffSeconds ~/ 60}');
}