Javascript 时间类型转换

29 阅读1分钟

时间类型转换

JavaScript在时间类型处理上,可能会遇到时区差异,导致时间值转换不一致的问题,下面提供一种忽略时区的时间类型转换方式

  /**
   * 将时间字符串转换为日期的 number 值 
   * @param dateStr yyyy-MM-DD HH:mm:ss 格式的时间
   * @returns 
   */
  static dateStrToTime(dateStr: string) {
    try {
      if (!dateStr) {
        return new Date().getTime();
      } else {
        const d = new Date(
          parseInt(dateStr.slice(0, 4)),   // year
          parseInt(dateStr.slice(4, 6)) - 1,  // month
          parseInt(dateStr.slice(6, 8)),    // day
          parseInt(dateStr.slice(8, 10)),   // hour
          parseInt(dateStr.slice(10, 12)), // minute
          parseInt(dateStr.slice(12, 14)));// second
        return d.getTime();
      }
    } catch (error) {
      console.log(error);
      return new Date().getTime();
    }
  }