js日期的格式化

2022-02-18 18:39:20 字數 2417 閱讀 4016

我們看控制台列印的關於date這個類

我們這裡可以看到內建方法沒有類似format這種方法,所以需要自己定義。

內建的方法:

var mydate = new date();

mydate.getyear();        //獲取當前年份(2位)

mydate.getfullyear();    //獲取完整的年份(4位,1970-????)

mydate.getmonth();       //獲取當前月份(0-11,0代表1月)

mydate.getdate();        //獲取當前日(1-31)

mydate.getday();         //獲取當前星期x(0-6,0代表星期天)

mydate.gettime();        //獲取當前時間(從1970.1.1開始的毫秒數)

mydate.gethours();       //獲取當前小時數(0-23)

mydate.getminutes();     //獲取當前分鐘數(0-59)

mydate.getseconds();     //獲取當前秒數(0-59)

mydate.getmilliseconds();    //獲取當前毫秒數(0-999)

mydate.tolocaledatestring();     //獲取當前日期

var mytime=mydate.tolocaletimestring();     //獲取當前時間

mydate.tolocalestring( );        //獲取日期與時間

利用這個內建的方法然後,拼成格式化的方法

看下這個部落格:

//

對date的擴充套件,將 date 轉化為指定格式的string

//月(m)、日(d)、小時(h)、分(m)、秒(s)、季度(q) 可以用 1-2 個佔位符,

//年(y)可以用 1-4 個佔位符,毫秒(s)只能用 1 個佔位符(是 1-3 位的數字)

//例子:

//(new date()).format("yyyy-mm-dd hh:mm:ss.s") ==> 2006-07-02 08:09:04.423

//(new date()).format("yyyy-m-d h:m:s.s") ==> 2006-7-2 8:9:4.18

date.prototype.format = function (fmt) ;

if (/(y+)/.test(fmt)) fmt = fmt.replace(regexp.$1, (this.getfullyear() + "").substr(4 - regexp.$1

.length));

for (var k in

o)

if (new regexp("

(" + k + "

)").test(fmt)) fmt = fmt.replace(regexp.$1, (regexp.$1.length == 1) ? (o[k]) : (("

00" + o[k]).substr(("" +o[k]).length)));

return

fmt;

}//呼叫:

var time1 = new date().format("

yyyy-mm-dd");

var time2 = new date().format("

yyyy-mm-dd hh:mm:ss

"); //這裡邊沒有星期的,簡單的使用

new date().format("yyyy/mm/dd hh:mm:ss")//這樣子也行

更容易記憶些:

時間的格式化

date.prototype.format = function

(fmt)

if(/(y+)/.test(fmt))

fmt = fmt.replace(regexp.$1,

(this.getfullyear()+"").substr(4-regexp.$1.length)

);for(var k in

o) }

return

fmt;

}console.log(

new date().format('yy-mm-dd hh-mm-ss'));

view code

計算時間差:

js日期格式化

日期格式化 使用方法1 var now new date var nowstr util.dateformat new date yyyy mm dd hh mm ss 使用方法2 var testdate new date var teststr util.dateformat new date ...

js日期格式化

方法一 對date的擴充套件,將 date 轉化為指定格式的string 月 m 日 d 小時 h 分 m 秒 s 季度 q 可以用 1 2 個佔位符,年 y 可以用 1 4 個佔位符,毫秒 s 只能用 1 個佔位符 是 1 3 位的數字 例子 new date format yyyy mm dd ...

Js格式化日期

對date的擴充套件,將 date 轉化為指定格式的string 月 m 日 d 小時 h 分 m 秒 s 季度 q 可以用 1 2 個佔位符,年 y 可以用 1 4 個佔位符,毫秒 s 只能用 1 個佔位符 是 1 3 位的數字 例子 new date format yyyy mm dd hh m...