/**
 * Created by rockyl on 2019-01-01.
 *
 * 时间相关常用方法
 */

import {format as stringFormat, supplement} from './utils'

/**
 * 时间戳转日期
 * @param ts
 */
export function ts2Date(ts) {
	let newDate:Date = new Date();
	newDate.setTime(ts);
	return newDate;
}

/**
 * 日期类转日期字符串
 * @param date
 * @param format
 */
export function dateToDateString(date:Date, format:string = '{0}/{1}/{2}'):string{
	return stringFormat(format, date.getFullYear(), supplement(date.getMonth() + 1, 2), supplement(date.getDate(), 2))
}

/**
 * 日期类转时间字符串
 * @param date
 * @param format
 */
export function dateToTimeString(date:Date, format:string = '{0}:{1}:{2}'):string{
	return stringFormat(format, supplement(date.getHours(), 2), supplement(date.getMinutes(), 2), supplement(date.getSeconds(), 2))
}

/**
 * 日期类转字符串
 * @param date
 * @param dayFormat
 * @param timeFormat
 */
export function dateToString(date: Date, dayFormat, timeFormat){
	return dateToDateString(date, dayFormat) + dateToTimeString(date, timeFormat);
}

/**
 * 时间戳转时间字符串
 * @param ts
 * @param format
 */
export function tsToTimeString(ts, format:string = '{0}:{1}:{2}'):string{
	let date = ts2Date(ts);
	return stringFormat(format, supplement(date.getHours(), 2), supplement(date.getMinutes(), 2), supplement(date.getSeconds(), 2))
}

/**
 * 秒转之间字符串
 * @param second
 * @param format
 * @param placeZero
 */
export function secondFormat(second:number, format:string = '{2}:{1}:{0}', placeZero:boolean = true):string {
	let ss:any = second % 60;
	let mm:any = Math.floor(second / 60) % 60;
	let hh:any = Math.floor(second / 3600) % 24;
	let dd:any = Math.floor(second / 3600 / 24);

	if (placeZero) {
		ss = supplement(ss, 2);
		mm = supplement(mm, 2);
		hh = supplement(hh, 2);
		dd = supplement(dd, 2);
	}

	return stringFormat(format, ss, mm, hh, dd);
}
