【问题标题】:Flutter DateTime.now is showing wrong time on real deviceFlutter DateTime.now 在真实设备上显示错误的时间
【发布时间】:2022-02-14 11:06:37
【问题描述】:

我在我的应用程序的时间选择器上显示DateTime.now();,但它显示的时间错误。我已经打印出时区,它显示 CET,但是当我输入 .toLocal 时,它显示了正确的设备时间,但是 .toLocal 不能像这样在 DateTime.now().toLocal(), 上使用,即使当前时间是 00:20,它仍然会给出错误的时间,例如 23:39 .我期待的是我希望应用程序跟踪正确的本地时间/设备时间,因为我不让用户选择过去的时间。需要注意的一点我想要 24 小时标准的时间,如果要具体说明我想要什么时区,那就是 GMT+1

到目前为止,这是我用于此功能的代码。

TimePickerSpinner(
                      is24HourMode: true,
                      isForce2Digits: true,
                      alignment: Alignment.center,
                      normalTextStyle: TextStyle(
                        fontSize: 14,
                        color: Colors.white,
                      ),
                      highlightedTextStyle:
                          TextStyle(fontSize: 16, color: Colors.black),
                      time: DateTime.now(),
                      onTimeChange: (time) {
                        DateFormat formatHour = DateFormat("HH");
                        String nowTimeHour = formatHour.format(DateTime.now());
                        String selectedTimeHour = formatHour.format(time);
                        DateFormat formatMints = DateFormat("mm");
                        String nowTimeMints =
                            formatMints.format(DateTime.now());
                        String selectedTimeMints = formatMints.format(time);
                        print(int.parse(nowTimeHour));
                        print(int.parse(selectedTimeHour));
                        if (int.parse(nowTimeHour) >
                            int.parse(selectedTimeHour)) {
                          setState(() {
                            isTimeCorrent = true;
                          });
                        } else if (int.parse(nowTimeHour) ==
                                int.parse(selectedTimeHour) &&
                            int.parse(nowTimeMints) >
                                int.parse(selectedTimeMints)) {
                          setState(() {
                            isTimeCorrent = true;
                          });
                        } else {
                          setState(() {
                            dateTimeSelected = time;
                            isTimeCorrent = false;
                          });
                        }
                      },
                    ),

【问题讨论】:

    标签: flutter dart datetime time flutter-layout


    【解决方案1】:

      var date = DateTime.now().toUtc();
    

    这将给出通用时间。因此,添加或减去 gmt 时间即可获得时间。(此处为 Gmt+1,因此将 UTC 时间加 1 小时即可获得正确时间)

      var date = DateTime.now().toUtc().add(Duration(hours:1));
    

    这里添加 Hours 1 => Gmt +1 代表 UTC 时间 + 小时

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-06-15
      • 2023-01-18
      • 2015-11-09
      • 1970-01-01
      • 2020-11-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多