flutterdart

Convert DateTime with TimeZone in Dart/Flutter


I just need to fetch DateTime to API with similar format like this one "Tue Oct 15 2024 00:00:00 GMT+0800 (Singapore Standard Time)". I used below code using timezone/timezone.dart and timezone/data/latest.dart package but no success.

  final currentDateTime = tz.TZDateTime.from(
      tz.TZDateTime.now(tz.local).copyWith(
        hour: 0,
        minute: 0,
        second: 0,
        millisecond: 0,
      ),
      tz.local,
    );

Solution

  • Use intl as follow:

    DateTime date = DateTime.now().toLocal(); // Get the current local date and time
      
      String timeZoneOffset = _formatTimeZoneOffset(date.timeZoneOffset);
      String formattedDate = DateFormat('EEE MMM d yyyy HH:mm:ss').format(date) + ' GMT$timeZoneOffset';
    

    //helper function to get formatTimeZoneOffset

    String _formatTimeZoneOffset(Duration offset) {
      final hours = offset.inHours.abs().toString().padLeft(2, '0');
      final minutes = (offset.inMinutes.abs() % 60).toString().padLeft(2, '0');
      final sign = offset.isNegative ? '-' : '+';
      return '$sign$hours$minutes';
    }