【问题标题】:How to get last 30 minutes,1 Hour time from the from current time in DART如何从 DART 中的当前时间获取最后 30 分钟、1 小时的时间
【发布时间】:2020-01-30 18:56:20
【问题描述】:

如何从 DART 中的当前时间获取最后 3 小时的时间

我通过这个得到当前时间

DateTime toTime = new DateTime.now();

我想获取最后 30 分钟前的最后 30 分钟,lastOneHour,lastThreeHour,last 6,last 12,last 24 time from the current time.

我试过这样做

    from = toTime.subtract(new Duration(hours: 0.5)).millisecondsSinceEpoch;
    //This is not working

我正在将这些结果转换为纪元时间。

【问题讨论】:

标签: datetime dart


【解决方案1】:

正如@julemand101 所指出的,Duration 将其命名为hours 参数作为int。传递一个 double 会抛出一个错误。相反,请编写如下代码:

DateTime curTime = new DateTime.now(); //Current local time
DateTime thirtyMinAgo = curTime.subtract(Duration(minutes: 30));
int thirtyMinAgoInMs = thirtyMinAgo.millisecondsSinceEpoch;
return thirtyMinAgoInMs;

【讨论】:

    【解决方案2】:

    试试这个包,Jiffy。灵感来自momentjs。它还考虑了闰年和每个月有多少天

    获取最后 30 分钟

    Jiffy().subtract(minutes: 30);
    
    // You can also add your DateTime object
    Jiffy(DateTime.now()).subtract(minutes: 30);
    

    获取最后 3 小时

    Jiffy().subtract(hours: 3);
    

    您也可以长达数月和数年

    var jiffy = Jiffy()
        .subtract(minutes: 30, hours: 3, days: 6, months: 2, years: 1);
    
    print(jiffy.dateTime);
    // Or you can format it on the go
    print(jiffy.format("dd, MMM yyyy"));
    print(jiffy.yMMMd);
    

    希望这会有所帮助。

    【讨论】:

      猜你喜欢
      • 2016-09-27
      • 2019-07-13
      • 2013-12-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多