js 時間戳和日期互轉

2021-09-07 12:17:19 字數 1575 閱讀 3483

// 獲取當前時間戳(以s為單位)

var timestamp = date.parse(new date());

timestamp = timestamp / 1000;

//當前時間戳為:1403149534

console.log("當前時間戳為:" + timestamp);

// 獲取某個時間格式的時間戳

var stringtime = "2014-07-10 10:21:12";

var timestamp2 = date.parse(new date(stringtime));

timestamp2 = timestamp2 / 1000;

//2014-07-10 10:21:12的時間戳為:1404958872

console.log(stringtime + "的時間戳為:" + timestamp2);

// 將當前時間換成時間格式字串

var timesta*** = 1403058804;

var newdate = new date();

newdate.settime(timesta*** * 1000);

// wed jun 18 2014

console.log(newdate.todatestring());

// wed, 18 jun 2014 02:33:24 gmt

console.log(newdate.togmtstring());

// 2014-06-18t02:33:24.000z

console.log(newdate.toisostring());

// 2014-06-18t02:33:24.000z

console.log(newdate.tojson());

// 2023年6月18日

console.log(newdate.tolocaledatestring());

// 2023年6月18日 上午10:33:24

console.log(newdate.tolocalestring());

// 上午10:33:24

console.log(newdate.tolocaletimestring());

// wed jun 18 2014 10:33:24 gmt+0800 (中國標準時間)

console.log(newdate.tostring());

// 10:33:24 gmt+0800 (中國標準時間)

console.log(newdate.totimestring());

// wed, 18 jun 2014 02:33:24 gmt

console.log(newdate.toutcstring());

date.prototype.format = function(format) ;

if (/(y+)/i.test(format))

for (var k in date)

}return format;

}console.log(newdate.format('yyyy-mm-dd h:m:s'));

日期和時間戳互轉

1 日期轉為時間戳 vardate newdate 2014 04 23 18 55 49 123 有三種方式獲取 vartime1 date.gettime vartime2 date.valueof vartime3 date.parse date console.log time1 13982...

js日期和時間戳之間相互轉換

1 將當前日期轉換為時間戳。var now new date console.log now.gettime 將當前日期轉換為時間戳,gettime 方法可返回距1970年1月1日之間的毫秒數。也可以使用 now 該效果等同於now.gettime 2 將指定日期轉換為時間戳。var t 2017 ...

JS日期時間與時間戳相互轉換

獲取當前的日期函式 傳入乙個時間戳,如果不傳則為當前時間 注意 如果是uinx時間戳記得乘於1000,比如php函式time 獲得的時間戳就要乘於1000 type string timestamp 要轉換的時間戳格式 1469504554276 returns 日期格式 2016 07 26 10...