abrev
abrev

Reputation: 325

Flutter: compare current date with date received from api

I have an app that receives some data from a api and i want to compare them, but dont know how to do it.

The date that comes from the api is in a different template, plus its a string, so i cant compare.

I want to show a error message if the received date is older than current date.

Here's how the api date comes (i have printed on console):

I/flutter ( 5190): 2004-08-26T01:00:00.000Z

And here is the DateTime.now on flutter:

I/flutter ( 5190): 2021-02-19 12:25:16.638505

Is there a way to compare them?

Upvotes: 2

Views: 1047

Answers (2)

Majid Ali
Majid Ali

Reputation: 495

You can parse the date from the api to the Datetimemethod(utc) in flutter and then you can compare.for example

String apidatetime= '2004-08-26T01:00:00.000Z';
DateTime.parse(apidatetime).isAtSameMomentAs(DateTimenow)

also check this

Upvotes: 1

You can convert the API date to a DateTime type and then compare the DateTimes like this:

DateTime.now().isAfter(apiDate)
DateTime.now().isBefore(apiDate)
DateTime.now().isAtSameMomentAs(apiDate)

Each of this lines will return a bool.

If te API date comes as Timestamp, you can convert it like this:

apiDate = apiTimestamp.toDate()

Upvotes: 0

Related Questions