1

I have a String date in format Month-Day-4DigitYear that I want to convert to DateTime in Flutter. I'm a novice coder, and I'm struggling to understand the api.flutter.dev Parse method example.

Below is the example. I just have a few issues. Android Studio throws multiple errors when I just create a class and put in this function. I think I understand the non-nullable issue, so I delete the ! and ? marks everywhere.

My issues are: what are _parseFormat, _brokenDownDateToValue, _withValue ?

All give errors and just declaring the first two and deleting the _withValue doesn't seem to do the trick, although removes all errors. It's like they've left out a key portion that I'm missing or there is a package I need to import the neither I nor Android Studio knows about. Can anyone decrypt this? I get very frustrated with flutter's documentation, as it always seems to give 80% of required info, assuming you already are clairvoyant on all other topics except this single one they are discussing. Gotta be a pro before reading the manual.

    // TODO(lrn): restrict incorrect values like  2003-02-29T50:70:80.
    // Or not, that may be a breaking change.
    static DateTime parse(String formattedString) {
      var re = _parseFormat;
      Match? match = re.firstMatch(formattedString);
      if (match != null) {
    int parseIntOrZero(String? matched) {
      if (matched == null) return 0;
      return int.parse(matched);
    }

    // Parses fractional second digits of '.(\d+)' into the combined
    // microseconds. We only use the first 6 digits because of DateTime
    // precision of 999 milliseconds and 999 microseconds.
    int parseMilliAndMicroseconds(String? matched) {
      if (matched == null) return 0;
      int length = matched.length;
      assert(length >= 1);
      int result = 0;
      for (int i = 0; i < 6; i++) {
        result *= 10;
        if (i < matched.length) {
          result += matched.codeUnitAt(i) ^ 0x30;
        }
      }
      return result;
    }

    int years = int.parse(match[1]!);
    int month = int.parse(match[2]!);
    int day = int.parse(match[3]!);
    int hour = parseIntOrZero(match[4]);
    int minute = parseIntOrZero(match[5]);
    int second = parseIntOrZero(match[6]);
    int milliAndMicroseconds = parseMilliAndMicroseconds(match[7]);
    int millisecond =
        milliAndMicroseconds ~/ Duration.microsecondsPerMillisecond;
    int microsecond = milliAndMicroseconds
        .remainder(Duration.microsecondsPerMillisecond) as int;
    bool isUtc = false;
    if (match[8] != null) {
      // timezone part
      isUtc = true;
      String? tzSign = match[9];
      if (tzSign != null) {
        // timezone other than 'Z' and 'z'.
        int sign = (tzSign == '-') ? -1 : 1;
        int hourDifference = int.parse(match[10]!);
        int minuteDifference = parseIntOrZero(match[11]);
        minuteDifference += 60 * hourDifference;
        minute -= sign * minuteDifference;
      }
    }
    int? value = _brokenDownDateToValue(years, month, day, hour, minute,
        second, millisecond, microsecond, isUtc);
    if (value == null) {
      throw FormatException("Time out of range", formattedString);
    }
    return DateTime._withValue(value, isUtc: isUtc);
  } else {
    throw FormatException("Invalid date format", formattedString);
  }
}
jbryanh
  • 1,193
  • 7
  • 17
  • Would like to point out that https://stackoverflow.com/questions/59877288/parse-string-to-datetime-in-flutter-dart answers my ultimate need, in a very simple way. However, I would still like to try to understand what I'm missing above. – jbryanh Nov 28 '20 at 17:11

2 Answers2

0

My issues are: what are _parseFormat, _brokenDownDateToValue, _withValue ?

These are objects or functions declared elsewhere in the lib which are private (the _ as the first character declares objects and functions as private) and therefore not shown in the documentation.

  • _parseFormat seems to be a regular expression.

  • _brokenDownDateToValue seems to be a function.

  • _withValue is a named constructor.

I think what you want to use is the following if you want to parse your date String to a DateTime object.

var date = "11-28-2020"; // Month-Day-4DigitYear
var dateTime = DateTime.parse(date.split('-').reversed.join());

See https://api.flutter.dev/flutter/dart-core/DateTime/parse.html for the accepted strings to be parsed.

Er1
  • 2,559
  • 1
  • 12
  • 24
  • I guess I'm struggling to understand how that example is supposed to be useful when three values are left undefined. _parseFormat and _brokenDownDateToValue and _withValue are nowhere to be found in any of the documentation that I can find. How's a beginner supposed to use this? – jbryanh Dec 02 '20 at 17:14
  • And thanks for the response. I solved my original, specific problem. However, this question is being asked to better understand how to read and use official Flutter documentation. With those three values left undefined, I don't understand how to use this documentation to gain anything. – jbryanh Dec 02 '20 at 17:15
  • @jbryanh When it comes to documentation on how to use the lib you usually don't have to look further than the 'main' page: https://api.flutter.dev/flutter/dart-core/DateTime-class.html It shows you some examples and info. If you want to know how a specific method works you can look into that. https://api.flutter.dev/flutter/dart-core/DateTime/parse.html for example gives you some more info on that method and which formats are supported. You rarely have to use the 'implementation' part of the doc. This just shows you what is going on in the lib if you use said method. Hope this helps a bit. – Er1 Dec 03 '20 at 09:21
  • Thanks for the response @Er1. You know, you referenced "the lib" twice now. Maybe that's what I'm missing? Is there a lib for flutter with all these examples that I need to reference? I just can't believe that they list these example methods in their documentation, referencing other functions that aren't shown that are integral to the example...these examples are useless without them. So maybe I'm such a beginner, that I just don't know where the library is...is there a library of these somewhere? A big GitHub example file? – jbryanh Dec 04 '20 at 13:39
  • @jbryanh The code you copied from the documentation page is not the code you should use if you want to use the library. It is referenced there to show you the inner workings of the functions the library provides for you to use. I don't know of any place which references every example you can use. You just have to look for examples and code you might need for yourself. You can look at all the core dart code on github if you want. But I doubt you want to if you're still a novice flutter/dart programmer. https://github.com/dart-lang/sdk/tree/master/sdk/lib/core – Er1 Dec 04 '20 at 22:41
0

I did find the full code example here.

It didn't use the name _parseFormat, instead just RegExp? And has _withValue and _brokenDownDateToValue declarations.

As I see it, there isn't a proper way to decode their example. The example is insufficient. A dictionary should not create definitions using words that can't be found elsewhere in the dictionary.

jbryanh
  • 1,193
  • 7
  • 17