如何将Google Firestore特定格式Timestamp字符串转为Dart Timestamp对象?
将Firestore Timestamp字符串转换为Dart Timestamp对象
要把格式为Timestamp(second=16698..., nanoseconds=187...)的字符串转成Dart的Timestamp对象,核心思路是提取字符串中的秒数和纳秒数,再用Firestore提供的构造方法生成对象,具体实现如下:
实现步骤
- 用正则表达式匹配字符串中的秒数(
second)和纳秒数(nanoseconds)数值 - 将提取到的字符串数值转为整数
- 通过
Timestamp.fromSecondsAndNanoseconds构造函数创建对象
代码示例
import 'package:cloud_firestore/cloud_firestore.dart'; Timestamp parseFirestoreTimestampString(String timestampStr) { // 匹配秒数和纳秒数,支持逗号前后任意空格 final regex = RegExp(r'second=(\d+)\s*,\s*nanoseconds=(\d+)'); final matchResult = regex.firstMatch(timestampStr); if (matchResult == null) { throw FormatException('输入的字符串不符合Timestamp格式'); } final seconds = int.parse(matchResult.group(1)!); final nanoseconds = int.parse(matchResult.group(2)!); return Timestamp.fromSecondsAndNanoseconds(seconds, nanoseconds); } // 测试使用 void main() { final testStr = 'Timestamp(second=1669852800, nanoseconds=187000000)'; final timestamp = parseFirestoreTimestampString(testStr); print(timestamp.toDate()); // 输出对应的DateTime对象,验证转换结果 }
注意事项
- 如果你的Timestamp字符串格式有细微差异(比如参数顺序不同、额外空格),可以调整正则表达式的匹配规则
- 若需要兼容格式不合法的情况,可以将抛出异常改为返回
null,根据业务需求处理
内容的提问来源于stack exchange,提问作者lookdadnomilk
相关产品推荐
相关产品推荐

