Flutter时间转换工具类

  • Post author:
  • Post category:其他


日期转换成时间戳

      ///日期转时间戳
      static int dateToTimestamp(String date, {isMicroseconds = false}) {
        DateTime dateTime = DateTime.parse(date);
        int timestamp = dateTime.millisecondsSinceEpoch;
        if (isMicroseconds) {
          timestamp = dateTime.microsecondsSinceEpoch;
        }
        return timestamp;
      }

时间戳转时间格式

  static DateTime timestampToDate(int timestamp) {
    DateTime dateTime = DateTime.now();
 
    ///如果是十三位时间戳返回这个
    if (timestamp.toString().length == 13) {
      dateTime = DateTime.fromMillisecondsSinceEpoch(timestamp);
    } else if (timestamp.toString().length == 16) {
      ///如果是十六位时间戳
      dateTime = DateTime.fromMicrosecondsSinceEpoch(timestamp);
    }
    return dateTime;
  }

将传进来的 时间戳/日期格式 转成 DateTime 格式

  static DateTime _changeTimeDate(time) {
    ///如果传进来的是字符串 13/16位 而且不包含-
    DateTime dateTime = DateTime.now();
    if (time is String) {
      if ((time.length == 13 || time.length == 16) && !time.contains("-")) {
        dateTime = timestampToDate(int.parse(time));
      } else {
        dateTime = DateTime.parse(time);
      }
    } else if (time is int) {
      dateTime = timestampToDate(time);
    }
    return dateTime;
  }



版权声明:本文为qqyang_原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。