tryParse static method

Timestamp? tryParse(
  1. String? text
)

parse or returns null

Implementation

static Timestamp? tryParse(String? text) {
  if (text != null) {
    // 2018-10-20T05:13:45.985343Z

    // remove after the seconds part
    var subSecondsStart = text.lastIndexOf('.') + 1;
    // not found
    if (subSecondsStart == 0) {
      var dateTime = DateTime.tryParse(text);
      if (dateTime == null) {
        return null;
      } else {
        return Timestamp.fromDateTime(dateTime);
      }
    }
    var dateTimeNoSubSeconds = StringBuffer();
    dateTimeNoSubSeconds.write(text.substring(0, subSecondsStart));
    // Replace sub seconds with 000, which is safe on all platforms
    dateTimeNoSubSeconds.write('000');

    // Read the sun seconds part
    var nanosString = StringBuffer();
    var i = subSecondsStart;
    for (; i < text.length; i++) {
      var char = text[i];
      if (_isDigit(char)) {
        // Never write more than 9 chars
        if (nanosString.length < 9) {
          nanosString.write(char);
        }
      } else {
        // Write the end (timezone info)
        dateTimeNoSubSeconds.write(text.substring(i));
        break;
      }
    }

    // Use DateTime parser for everything but subseconds
    var dateTime = DateTime.tryParse(dateTimeNoSubSeconds.toString());
    if (dateTime == null) {
      return null;
    }

    // Never write less than 9 chars
    while (nanosString.length < 9) {
      nanosString.write('0');
    }

    var seconds = (dateTime.millisecondsSinceEpoch / 1000).floor();
    var nanoseconds = int.tryParse(nanosString.toString())!;
    return Timestamp(seconds, nanoseconds);
  }
  return null;
}