function timestamp(time){
var date = new Date(time); //傳個時間戳過去就能夠了
Y = date.getFullYear() + '-';
M = (date.getMonth()+1 < 10 ? '0'+(date.getMonth()+1) : date.getMonth()+1) + '-';
D = date.getDate() + ' ';php
return Y+M+D; //2014-04-23 18:55:49:123
}函數
1. js將時間戳轉換成日期格式
// 簡單的一句代碼
var date = new Date(時間戳); //獲取一個時間對象 注意:若是是uinx時間戳記得乘於1000。好比php函數time()得到的時間戳就要乘於1000
/**
1. 下面是獲取時間日期的方法,須要什麼樣的格式本身拼接起來就行了
*/
date.getFullYear(); // 獲取完整的年份(4位,1970)
date.getMonth(); // 獲取月份(0-11,0表明1月,用的時候記得加上1)
date.getDate(); // 獲取日(1-31)
date.getTime(); // 獲取時間(從1970.1.1開始的毫秒數)
date.getHours(); // 獲取小時數(0-23)
date.getMinutes(); // 獲取分鐘數(0-59)
date.getSeconds(); // 獲取秒數(0-59)
例子
// 好比須要這樣的格式 yyyy-MM-dd hh:mm:ss
var date = new Date(1398250549490);
Y = date.getFullYear() + '-';
M = (date.getMonth()+1 < 10 ? '0'+(date.getMonth()+1) : date.getMonth()+1) + '-';
D = date.getDate() + ' ';
h = date.getHours() + ':';
m = date.getMinutes() + ':';
s = date.getSeconds();
console.log(Y+M+D+h+m+s); //呀麻碟
// 輸出結果:2014-04-23 18:55:49
2. 將日期格式轉換成時間戳
// 也很簡單
var strtime = '2014-04-23 18:55:49:123';
var date = new Date(strtime); //傳入一個時間格式,若是不傳入就是獲取如今的時間了,這樣作不兼容火狐。
// 能夠這樣作
var arr = strtime.replace(/ |:/g, '-').split('-');
date = new Date(Date.UTC(arr[1], arr[2], arr[3], arr[4], arr[5]));
// 有三種方式獲取,在後面會講到三種方式的區別
time1 = date.getTime();
time2 = date.valueOf();
time3 = Date.parse(date);
/*
三種獲取的區別:
第1、第二種:會精確到毫秒
第三種:只能精確到秒,毫秒將用0來代替
好比上面代碼輸出的結果(一眼就能看出區別):
1398250549123
1398250549123
1398250549000
*/
3. 注意
獲取到的時間戳除於1000就能夠得到unix的時間戳了,在傳值給PHP時用獲得 ui