Home > Software engineering >  Datetime currentTime issue
Datetime currentTime issue

Time:07-21

I have a code like this:

onPressed: isClick
                    ? () async {
                        isClick = false;
                        final DateTime dateCreated = DateTime.now();
                        setState(() {
                          dateCreated;
                        });
                        final userIp = await UserService.getIp();
                        final user = User(
                            name: _nameController.text,
                            surname: _surnameController.text,
                            email: _emailController.text,
                            year: _selectedValue,
                            dateCreated: DateFormat('dd/MM/y - HH:mm:ss').format(dateCreated),
                            ipAddress: userIp);
                        hasInternet = await InternetConnectionChecker().hasConnection;
                        await UserService.insert([user.toJson()]);
                        if (hasInternet) {
                          showToast(StringConstants.registerOkayText, duration: 2, gravity: Toast.bottom);
                        } else {
                          showToast(StringConstants.registerNotOkayText, duration: 5, gravity: Toast.bottom);
                        }
                      }
                    : null,

The time is now 16.15 but the code prints the time as 13.14. How can I solve this? GMT?

CodePudding user response:

If you want mobile time and want to format just use this plugin intl: ^0.17.0

DateTime currentDate = DateTime.now();

String s = DateFormat('yyyy-MM-dd').format(DateFormat('yyyy-MM-dd').parse(date));

In the stirng s you will get the current date

Or if you want to get the current internet time you just use

ntp: ^2.0.0

final int offset = await NTP.getNtpOffset(
          localTime: DateTime.now(), lookUpAddress: "time.google.com");
      DateTime internetTime =
          DateTime.now().add(Duration(milliseconds: offset));

here you will get the current time and date in internetTime

CodePudding user response:

Your code of getting the date time looks good to me. It should give you the current local time of your computer. So obviously it can be due to the time settings of your computer. please check if that is configured to different timezone or may be if VPN check the timezone of vpn. Try this to see what is the timezone of your computer. print(dateTime.timeZoneName); print(dateTime.timeZoneOffset);

  • Related