How to get last 30 minutes,1 Hour time from the from current time in DART

Viewed 760

how can I get the last 3 hours time from the current time in DART

I am getting the current time by this

DateTime toTime = new DateTime.now();

I want to get last last 30minutes before,lastOneHour,lastThreeHour,last 6,last 12,last 24 time from the current time.

I tried doing like this

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

I am converting those result to epochtime.

2 Answers

As @julemand101 pointed out, Duration has its named hours parameter as an int. Passing a double will toss an error. Instead, write your code something like this:

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

Try out this package, Jiffy. Inspired by momentjs. It also takes into account the leap years and how many days there are in each month

To get the last 30 minutes

Jiffy().subtract(minutes: 30);

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

To get the last 3 hours

Jiffy().subtract(hours: 3);

You can also get up to months and years

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);

Hope this helped.

Related