時間戳基礎知識
時間戳是指格林威治時間1970年01月01日00時00分00秒(北京時間1970年01月01日08時00分00秒)起至現在的總秒數,也就是說,每過一秒,當前時間戳加1,所以可以根據這個進行時間的關系運算
php中的時間格式處理
獲取當前時間戳
time();
將時間戳轉換為標準時間格式
date('Y-m-d H:i:s', 1491447794)
將標準時間格式轉換為時間戳
strtotime("2017-04-06 11:03:14")
js中的事件格式處理
js有時間對象,實例化一下,打印出來看看,這個時間對象有很多方法,js對于事件格式的處理都是基于這個對象,以及對象的方法來進行字符串處理。
console.log(new Date());//Thu Apr 06 2017 11:49:48 GMT+0800 (中國標準時間)
獲取當前時間戳
Math.ceil(Date.parse(new Date()) / 1000);// Date轉換出來的是毫秒級時間戳,所以要除以1000
時間戳轉換日期格式
function getDate(time) {
var date = new Date(parseInt(time) * 1000).toLocaleString();
return date;
}
根據時間戳獲得年月日 或時分秒
// 一位數前補零
function getTen(num){
if ( num < 10) {
return "0" + num;
}
return num;
}
// 獲取年月日格式
function onlyDate(time) {
var date = new Date(parseInt(time)*1000);
var year = date.getFullYear();
var month = getTen(date.getMonth()+1);
var day = getTen(date.getDate());
return year + '-' + month + '-' + day;
}
// 獲取時分秒格式
function onlyTime(time){
var date = new Date(parseInt(time)*1000);
var hour = getTen(date.getHours());
var minutes = getTen(date.getMinutes());
return hour + ':' + minutes;
}
根據時間格式獲取時分秒
// 根據date格式獲得時分秒
function toSecond(date){
var date = new Date(date);
var hour = getTen(date.getHours());
var minutes = getTen(date.getMinutes());
var second = getTen(date.getSeconds());
return hour + ':' + minutes + ':' + second;
}
// 根據date格式獲得年月日
function toDate(date){
var date = new Date(date);
var year = date.getFullYear();
var month = getTen(date.getMonth()+1);
var day = getTen(date.getDate());
return year + '-' + month + '-' + day;
}