js時間戳與日期格式之間相互轉換

2021-09-28 11:36:06 字數 2274 閱讀 4932

將時間戳轉換成日期格式

// 簡單的一句**

var date = new date(時間戳); //獲取乙個時間物件

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 =

newdate

(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

將日期格式轉換成時間戳

//可以這樣做

var strtime = 『2014-04-23 18:55:49:123』;

var date = new date(strtime);

//傳入乙個時間格式,如果不傳入就是獲取現在的時間了,這樣做不相容火狐。

// 可以這樣做

var date = new date(strtime.replace(/-/g, 『/』));

// 有三種方式獲取,在後面會講到三種方式的區別

time1 = date.gettime();

time2 = date.valueof();

time3 = date.parse(date);

/*三種獲取的區別:

第一、第二種:會精確到毫秒

第三種:只能精確到秒,毫秒將用0來代替

比如上面**輸出的結果(一眼就能看出區別):

1398250549123

1398250549123

1398250549000

*/

date()引數形式有7種

new date(「month dd,yyyy hh:mm:ss」);

new date(「month dd,yyyy」);

new date(「yyyy/mm/dd hh:mm:ss」);

new date(「yyyy/mm/dd」);

new date(yyyy,mth,dd,hh,mm,ss);

new date(yyyy,mth,dd);

new date(ms);

比如:

new

date

("september 16,2016 14:15:05");

newdate

("september 16,2016");

newdate

("2016/09/16 14:15:05");

newdate

("2016/09/16");

newdate

(2016,8

,16,14

,15,5

);// 月份從0~11

newdate

(2016,8

,16);

newdate

(1474006780

);

時間戳與日期格式相互轉換

import time 建立乙個時間戳 t 1533880334 1.使用time.localtime將時間戳轉成日期格式 t time.localtime t time.struct time tm year 2018,tm mon 8,tm mday 10,tm hour 13,tm min 5...

js時間戳與日期格式的相互轉換

function timestamptotime timestamp timestamptotime 1403058804 console.log timestamptotime 1403058804 2014 06 18 10 33 24注意 如果是unix時間戳記得乘以1000。比如 php函式...

js時間戳與日期格式的相互轉換

下面總結一下js中時間戳與日期格式的相互轉換 1.將時間戳轉換成日期格式 時間戳轉 日期 console.log this.timestamptotime new date gettime yyyy mm dd hh mm ss timestamptotime timestamp,format co...