flutter dart语言中Time Span的等价物是什么?

ozxc1zmp  于 2023-03-03  发布在  Flutter
关注(0)|答案(2)|浏览(151)

dart中使用什么数据类型来代替C#中的TimeSpan数据类型?

pbpqsu0x

pbpqsu0x1#

它是Duration
例如:

void main(List<String> args) {
  // Define two dates.
  DateTime date1 = new DateTime(2010, 1, 1, 8, 0, 15);
  DateTime date2 = new DateTime(2010, 8, 18, 13, 30, 30);

  // Calculate the interval between the two dates.
  Duration interval = date2.difference(date1);
  print('$date2 - $date1 = $interval');

  // Display individual properties of the resulting TimeSpan object.
  print('Total Number of Days: ${interval.inDays}');
  print('Total Number of Hours: ${interval.inHours}');
  print('Total Number of Minutes: ${interval.inMinutes}');
  print('Total Number of Seconds: ${interval.inSeconds}');
  print('Total Number of Milliseconds: ${interval.inMilliseconds}');
}

结果将是:

2010-08-18 13:30:30.000 - 2010-01-01 08:00:15.000 = 5501:30:15.000000
Total Number of Days: 229
Total Number of Hours: 5501
Total Number of Minutes: 330090
Total Number of Seconds: 19805415
Total Number of Milliseconds: 19805415000
yduiuuwa

yduiuuwa2#

在Flutter/Dart应用中从C# Timespan字符串Map到持续时间
如果您有一个基于C#的API/服务器,它提供具有TimeSpan属性的数据传输对象,则在客户端阅读Dart/Flutter应用程序中的数据可能是一个挑战,因为Dart当前不提供Duration parse()函数。TimeSpan字符串格式为[-]d.hh:mm:ss.ff
下面的代码提供了一个解析方法,它可以用两种不同的模式实现(可以选择String扩展或DurationExt方法),test 类展示了如何使用这两种模式构建fromMap()解决方案:

import 'dart:convert';
//
// extension on string class to parse/construct a duration
//
extension DurationParsing on String {
  Duration parseDuration() {
    // accepts C# TimeSpan [-]d.hh:mm:ss.ff
    final regexp = RegExp(
        r'(?:(?<ne>-))?(?:(?:(?<dd>0*[0-9]+)[.])?(?:(?<HH>0*[2][0-3]|0*[1][0-9]|0*[0-9])[:]))?(?<mm>(?<=:)0*[0-5]?[0-9]|0*[5-9]?[0-9](?=[:]))(?:[:](?<ss>0*[0-5]?[0-9](?:[.][0-9]{0,7})?))?');

    final match = regexp.firstMatch(this);
    int days = int.parse((match?.namedGroup('dd')) ?? "0");
    int hours = int.parse((match?.namedGroup('HH')) ?? "0");
    int mins = int.parse((match?.namedGroup('mm')) ?? "0");
    int usecs = (double.parse((match?.namedGroup('ss')) ?? "0.0") * 1000000).round();
    bool negative = match?.namedGroup('ne') == "-";

    final duration = Duration(days: days, hours: hours, minutes: mins, microseconds: usecs);

    return negative ? Duration.zero - duration : duration;
  }
}

// static extensions are not allowed, so closest might be
// this pattern implemented using method above
extension DurationExt on Duration {
  static Duration fromString(String str) {
    return str.parseDuration();
  }
}

//usage example with both patterns
class Test {
  final Duration duration1;
  final Duration duration2;

  Test({ required this.duration1, required this.duration2});

  // typical fromMap to process network sourced data, showing both patterns
  factory Test.fromMap(Map<String, dynamic> map) {
    return Test(
      duration1: map['duration1'] != null ? (map['duration1'] as String).parseDuration() : Duration.zero,
      duration2: map['duration2'] != null ? DurationExt.fromString(map['duration2'] as String) : Duration.zero,
    );
  }

 factory Test.fromJson(String source) => Test.fromMap(json.decode(source) as Map<String, dynamic>);

}

相关问题