时间戳与时间的相互转换的几种方式

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-scale=1.0">

<meta http-equiv="X-UA-Compatible" content="ie=edge">

<title>Document</title>

</head>

<body>

<script>

//时间转时间戳的四种方式

// 1.Date.parse()

let nowTime1 = Date.parse(new Date()); //不推荐这种方法;毫秒会直接转为000

console.log(nowTime1);

//2.valueOf()

let nowTime2 = (new Date()).valueOf(); //过valueOf()函数返回指定对象的原始值获得准确的时间戳值

console.log(nowTime2);

//3.getTime()

let nowTime3 = (new Date()).getTime(); //通过原型方法直接获取毫秒值,准确值高

console.log(nowTime3);

//4.Number()

let nowTime4 = Number(new Date); //将时间转化为一个number类型的数值,即时间戳

console.log(nowTime4);

//时间戳转换为任意格式的时间

//1.

function localDate(value) {

let date = new Date(value),

Month = date.getMonth() + 1,

Day = date.getDate(),

//Day=parseInt(date / 60 / 60 / 24, 10);

Hours = date.getHours(),

// Hours = parseInt((date / 60 / 60) % 24, 10);

Minutes = date.getMinutes(),

// Minutes = parseInt((date / 60) % 60, 10);

Seconds = date.getSeconds(),

//Seconds = parseInt(date % 60, 10);

Y = date.getFullYear() + '-',

M = Month >= 10 ? Month + '-' : '0' + Month + '-',

D = Day >= 10 ? Day + ' ' : '0' + Day + ' ',

H = Hours >= 10 ? Hours + ':' : '0' + Hours + ':',

Mi = Minutes >= 10 ? Minutes + ':' : '0' + Minutes + ':',

S = Seconds >= 10 ? Seconds : '0' + Seconds;

return Y + M + D + H + Mi + S;

}

console.log(localDate(nowTime1));

console.log(localDate(nowTime2));

console.log(localDate(nowTime3));

console.log(localDate(nowTime4));


 

//2.封装一个转换日期格式的方法

function localDate2(value) {

let date = new Date(value),

Month = zeroPadding(date.getMonth() + 1, 2)+'-',

Day = zeroPadding(date.getDate(), 2)+' ',

//Day=parseInt(date / 60 / 60 / 24, 10); //第二种转换时间的算法

Hours = zeroPadding(date.getHours(),2)+':',

// Hours = parseInt((date / 60 / 60) % 24, 10);

Minutes = zeroPadding(date.getMinutes(), 2)+':',

// Minutes = parseInt((date / 60) % 60, 10);

Seconds = zeroPadding(date.getSeconds(), 2),

//Seconds = parseInt(date % 60, 10);

Year = zeroPadding(date.getFullYear(), 4)+'-';

return Year + Month + Day + Hours + Minutes + Seconds;

}

console.log(localDate2(nowTime1));

console.log(localDate2(nowTime2));

console.log(localDate2(nowTime3));

console.log(localDate2(nowTime4));

//这个方法进行补0;当值为个位数时,前面加0;

function zeroPadding(num, digit) {

let zero = "";

for (var i = 0; i < digit; i++) {

zero += "0";

}

return (zero + num).slice(-digit);

}

// PS:微信小程序时间转时间戳时 iphone手机的兼容性;

// IOS系统不支持2017-01-01格式的时间导致的,所以要先用正则替换2017-01-01日期格式为2017/01/01后问题解决

</script>

</body>

</html>

猜你喜欢

转载自blog.csdn.net/dwb123456123456/article/details/82253667