/**
 * 将 RFC3339 标准转成常用时间格式
 *
 * ```js
 * rfc33392time('2020-07-31T14:27:10.035542+08:00')
 * // 2020-07-31 14:28:12
 * ```
 *
 * @param {string} dateStr RFC3339 标准时间字符串
 * @returns {string} 常用时间格式
 */
export const rfc33392time = (dateStr: string): string => {
  const date = new Date(dateStr).toJSON()
  return (new Date(+new Date(date) + 8 * 3600 * 1000))
    .toISOString()
    .replace(/T/g, ' ')
    .replace(/\.[\d]{3}Z/, '')
    .slice(0,16)
}

const TIME_OFFSET = (() => {
  const info = (new Date().toString()).match(/GMT\+(\d{2})(\d{2})/)
  return `+${info![1]} : ${info![2]}`
})()

/**
 * 将常用时间格式转为 RFC3339 标准
 *
 * ```js
 * time2rfc3339('2020-07-31 14:28:12')
 * // 2020-07-31T14:27:10.035542+08:00
 * ```
 *
 * @param {string} date 常用时间格式
 * @returns {string} RFC3339 标准时间
 */
export function time2rfc3339(date: string) {
  const time = new Date(date)
  const y = time.getFullYear()
  const m = time.getMonth() + 1 < 10 ? `0${time.getMonth() + 1}` : (time.getMonth() + 1)
  const d = time.getDate() < 10 ? `0${time.getDate()}` : time.getDate()
  const hh = time.getHours() < 10 ? `0${time.getHours()}` : time.getHours()
  const mm = time.getMinutes() < 10 ? `0${time.getMinutes()}` : time.getMinutes()
  const ss = time.getSeconds() < 10 ? `0${time.getSeconds()}` : time.getSeconds()
  // const endDate = y + '-' + m + '-' + d + ' ' + hh + ':' + mm + ':' + ss
  // endDate = endDate.replace(/\s+/g, 'T') + '+08:00'
  // return endDate
  return `${y}-${m}-${d}T${hh}:${mm}:${ss}${TIME_OFFSET}`
}
