flutter - DateTime.now() not same in my local time
Asked Answered
B

2

10

I have a case to check the store opening-closed hours. Im solve this using the code below:

final _openHours = 09;
final _openMinute = 00;
final _closeHours = 15;
final _closeMinute = 00;

var now = DateTime.now();
print(now);

var _open = new DateTime(now.year, now.month, now.day, _openHours, _openMinute, now.second);
var _close = new DateTime(now.year, now.month, now.day, _closeHours, _closeMinute, now.second);

now.isAfter(_open) && now.isBefore(_close) {
  print("online");  
} else {
  print("offline");
}

but when I print DateTime.now(), this time does not match the current time? I have tried it using manually input currently time to make sure the code checks the opening and closing hours, and its works.

Bardo answered 22/1, 2019 at 0:30 Comment(4)
DateTime.now should return an instant in time anchored in the local time zone of the host. Is it running on a server?Spore
@Spore Yeah i think so, no.. just locally. the difference is a few hoursBardo
Are you running in an emulator? Is the device in the emulator set to a different timezone? Does print(DateTime.now().timeZoneName); look correct to you?Percuss
well, I forgot setup emulators date settingsBardo
U
16

Well, this waste me lot of time, I answer it to help someone may encounter same problem. After modify emulator settings, it work OK. enter image description here

Unipod answered 7/10, 2020 at 4:9 Comment(1)
You may need to turn on "Set time automatically" as well as the emulator may not have the right time.Acotyledon
K
0

This answer may not be useful for this specific scenario, but it is what worked for me when dealing with different time zone readings in the Windows app, despite having the correct data from the DB.

Let's say I had from the DB the time 8:30 AM and the Windows app was reading 11:30 AM, a 3 hours time difference.

I had to change the code from:

DateTime.parse(json["ExpeditionDateTime"])

to:

DateTime.parse(json["ExpeditionDateTime"]).toLocal()
Kwarteng answered 13/8 at 11:49 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.