skip to Main Content

I want to format my DateTime.now() to March 19, 2024 at 11:06:32 AM UTC+5" but its Data type should be DateTime.

I am getting Date in that format but it is in String:

String formattedDate = DateFormat("MMMM dd, yyyy 'at' hh:mm:ss a 'UTC+5'").format(DateTime.now().toUtc().add(Duration(hours: 5)));

So, i want that String in DateTime Data Type which i am unable to do.

2

Answers


  1. You can generalize and use 'UTC'Z instead of 'UTC+5', and for ease of use define your format as a variable

    DateFormat specialFormat = DateFormat("MMMM d, yyyy 'at' hh:mm:ss a 'UTC'Z");
    

    Now you need to use the DateFormat.parse() method

    try {
        String inputString = "March 19, 2024 at 11:06:32 AM UTC+5";
        DateTime parsedDate = specialFormat.parse(inputString);
    } catch (e) {
        print("Error parsing date: $e");
    }
    
    Login or Signup to reply.
  2. I’m not aware of any built-in way to print UTC offsets nicely, so I think you’ll have to format DateTime.timeZoneOffset manually:

    import 'package:intl/intl.dart';
    
    extension on DateFormat {
      String formatWithOffset(DateTime dateTime) {
        var offset = dateTime.timeZoneOffset;
        var offsetStringParts = ['UTC'];
        if (offset != Duration.zero) {
          if (offset.isNegative) {
            offsetStringParts.add('-');
            offset = -offset;
          } else {
            offsetStringParts.add('+');
          }
    
          if (offset.inMinutes % 60 == 0) {
            offsetStringParts.add('${offset.inHours}');
          } else {
            offsetStringParts
              ..add('${offset.inHours}'.padLeft(2, '0'))
              ..add('${offset.inMinutes % 60}'.padLeft(2, '0'));
          }
        }
    
        return '${format(dateTime)} ${offsetStringParts.join()}';
      }
    }
    
    /// A [DateTime] object that overrides [timeZoneOffset].
    class FakeDateTime extends DateTime {
      @override
      Duration timeZoneOffset = Duration.zero;
    
      FakeDateTime.from(DateTime original)
          : super(
              original.year,
              original.month,
              original.day,
              original.hour,
              original.minute,
              original.second,
              original.millisecond,
              original.microsecond,
            );
    }
    
    void main() {
      var now = FakeDateTime.from(DateTime.now());
      var format = DateFormat("MMMM dd, yyyy 'at' hh:mm:ss a");
    
      // Prints: 2024-04-21 12:55:15.138
      print(now);
    
      // Prints: April 21, 2024 at 12:55:15 PM UTC
      print(format.formatWithOffset(now));
    
      // Prints: April 21, 2024 at 12:55:15 PM UTC+5
      now.timeZoneOffset = const Duration(hours: 5);
      print(format.formatWithOffset(now));
    
      // Prints: April 21, 2024 at 12:55:15 PM UTC-0715
      now.timeZoneOffset = -const Duration(hours: 7, minutes: 15);
      print(format.formatWithOffset(now));
    }
    

    The formatWithOffset implementation could be simplified by removing the different formatting cases (currently it handles time zone offsets of zero, time zone offsets with a whole number of hours, and time zone offsets with a non-zero minute component differently).

    Note that if you want to handle DateTime objects in a time zone other than the local time zone, you probably should be using TZDateTime objects from package:timezone instead.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search