skip to Main Content

What is this Date time:
"2024-08-29 13:15:05 +0000 UTC" OR
"2024-08-29 01:33:40.774468453 -0400 EDT"

How I can convert & reformat it in flutter, what is the date format it will take ??

tried native flutter classes & intl library

2

Answers


  1. You have to add the intl package to your pubspec.yaml:

    You can use the DateTime.parse() method to convert the date strings into DateTime objects. However, since the second format includes fractional seconds and a timezone, you might want to use DateTime.parse() directly, as it supports ISO 8601 format well.

      String dateString1 = "2024-08-29 13:15:05 +0000 UTC";
      String dateString2 = "2024-08-29 01:33:40.774468453 -0400 EDT";
    
      // Parse the date strings
      DateTime dateTime1 = DateTime.parse(dateString1.replaceAll(" UTC", ""));
      DateTime dateTime2 = DateTime.parse(dateString2);
    
      // Format the dates
      String formattedDate1 = DateFormat('yyyy-MM-dd – kk:mm').format(dateTime1);
      String formattedDate2 = DateFormat('yyyy-MM-dd – kk:mm').format(dateTime2);
    
      print("Formatted Date 1: $formattedDate1");
      print("Formatted Date 2: $formattedDate2");
    
    Login or Signup to reply.
  2. To handle dynamic fractional seconds in your date strings, you can extract the fractional seconds separately and add them to the parsed DateTime object.

      String dateString = "2024-08-29 01:33:40.774468453 -0400 EDT";
    
      // Remove the timezone abbreviation at the end
      String cleanDate = dateString.replaceAll(RegExp(r's[A-Z]{3,4}$'), '');
    
      // Extract fractional seconds
      RegExp regex = RegExp(r'.(d+)');
      Match? match = regex.firstMatch(cleanDate);
      String fractionalPart = match != null ? match.group(1)! : '';
      cleanDate = cleanDate.replaceAll(RegExp(r'.d+'), '');
    
      // Define the date format without fractional seconds
      DateFormat dateFormat = DateFormat("yyyy-MM-dd HH:mm:ss ZZZ");
    
      // Parse the date string
      DateTime dateTime = dateFormat.parse(cleanDate, true); // true for UTC
    
      // Add fractional seconds to the DateTime object
      if (fractionalPart.isNotEmpty) {
        // Convert fractional seconds to microseconds
        int microseconds =
            int.parse(fractionalPart.padRight(6, '0').substring(0, 6));
        dateTime = dateTime.add(Duration(microseconds: microseconds));
      }
    
      print("Parsed DateTime: $dateTime");
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search