時間常用api

2022-04-11 23:37:19 字數 1872 閱讀 4423

1.常用api

建立 date 物件  -  年  -  月  -  日   -  小時  -  分  -  秒 -  星期

var now=new date()

var year = now.getfullyear();

var month = now.getmonth();       (月 :0 - 11 ,處理: month = month + 1;)

var date = now.getdate();  // 獲取當前時間對應 月 的天數

var hour = now.gethours();

var minu = now.getminutes();

var sec = now.getseconds();

var day = now.getday();  (星期:0 - 6 ,處理:var arr_week = new array("星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六");

week = arr_week[day];

tips:

月份是從0開始算的,省略日,則預設是按1日來算的。因此 new date(2019, 0) 就是 2019/1/1

獲取上個月

function

getlastmonth(date)

lastmonthlastday = (new date(lastmonthyear, lastmonth, 0)).getdate();

lastmonth = lastmonth - 0 >= 10 ? lastmonth : '0' +lastmonth

lastmonthlastday = lastmonthlastday - 0 >= 10 ? lastmonthlastday : '0' +lastmonthlastday

return

}

view code

格式化日期

export function

parsetime(time, cformat)

const format = cformat || '-- ::'let date;

if(!time)

if (typeof time === 'object')

else

/.test(fotmattime))

else

}else

if(/\dt\d/ig.test(time))

} const formatobj =

const time_str = format.replace(//g, (result, key) =>

return value || 0})

return

time_str

}

view code

2.擴充套件與實踐

2.1 可根據本地時間把 date 物件轉換為字串

new date().tolocalestring()    //   "2018/8/29 下午7:45:50"

2.2 返回距 1970 年 1 月 1 日之間的毫秒數

new date().gettime()     //    1535543394634

2.3 js中獲得指定日期前或後幾天對應的日期

var d = new date();

d.setdate(d.getdate() - 2);

d.tolocaledatestring()  // "2018/11/17"

var c = new date(2017,0,1);  //   mouth  0  - 11

c.setdate(c.getdate() - 2);

c.tolocaledatestring()   //  "2016/12/30"

js日期時間API

date物件 封裝乙個時間點資料,並且提供對時間或日期的api 1 建立 var date new date api 每個分量都有一段get,set方法.獲取 設定該分量的值.時間做加法 var second date.gettime 返回時間毫秒數 varnextms second 5 60 10...

陣列常用API

var color red green blue var color2 yellow black brown var color3 color.concat color2 concat 是將引數傳遞進來的陣列內容 拼接到呼叫者後面,不修改原陣列 var color4 color.tostring 陣...

陣列常用API

陣列常用api push 末尾新增 pop 末尾刪除 unshift 開頭新增 concat 開頭刪除 reserver 顛倒陣列 sort 排序 join 將陣列轉換成字串 splice 刪除 替換 插入 slice 切割陣列 indexof data,start 查詢關鍵字 es5新增 第乙個下...