Flutter UTC 时间转换

2,393 阅读1分钟

在项目开发过程中需要将本地时间转为UTC字符串,在某些时候又需要将UTC字符串转为本地时间,发现网上关于UTC时间转换的文章比较少,我这里来总结一下。

我们这边后台返回的UTC时间是这种格式:2021-11-05T12:45:12,上传给后台也是要这种格式,关于UTC时间的介绍可自行百度,本文只介绍本地时间转UTC时间、UTC字符串转本地时间。

  1. 本地时间转UTC时间 这个比较简单
static String changeToUtcTimeStr([DateTime localTime]) {
  if (localTime == null) {
    localTime = DateTime.now();
  }
  return localTime.toUtc().toString().replaceFirst(' ', 'T');
}
  1. UTC字符串转本地时间 参考自文章

思路:先获取本地时区的偏移量,例如中国北京是东八区,转成字符串‘-0800’,拼接在UTC字符串后面,然后调用DateTime.parse('2021-11-05T12:45:12-0800'),"-"代表向东边偏移,"+"代表向西边偏移,"08"代表8个小时,"00"代表分钟。

static String changeUtcStrToLocalStr(String utcStr) {
  if (utcStr == null || utcStr == '') {
    return '';
  }

  Duration dur = DateTime.now().timeZoneOffset;//获取本地时区偏移
  List timeZoneHourAndMinute = dur.toString().split(':');
  String subFormat = '';
  if ((timeZoneHourAndMinute[0] as String).contains('-')) {
    if ((timeZoneHourAndMinute[0] as String).length == 2) {//将-8 转成 +08
      subFormat = '0' + (timeZoneHourAndMinute[0] as String).split('-')[1];
    } else {
      subFormat = timeZoneHourAndMinute[0].toString().split('-')[1];
    }
    subFormat = '+' + subFormat;
  } else {
    if ((timeZoneHourAndMinute[0] as String).length == 1) {//将8 转成 -08
      subFormat = '0' + timeZoneHourAndMinute[0];
    } else {
      subFormat = timeZoneHourAndMinute[0];
    }
    subFormat = '-' + subFormat;
  }
  subFormat = subFormat + timeZoneHourAndMinute[1];
  String toFormatUtcStr = utcStr + subFormat;
  print(toFormatUtcStr);
  DateTime utcTime = DateTime.parse(toFormatUtcStr);
  return utcTime.toString().split('.')[0];
}