js獲取當前時間的年月日時分秒以及時間的格式化

2022-07-24 10:00:21 字數 2568 閱讀 3216

1.獲取當前時間

var date = new date();

2.獲取時間中的年月日時分秒及星期

date.getyear();                    //

獲取當前年份(2位)

date.getfullyear(); //

獲取完整的年份(4位,1970-至今)

date.getmonth(); //

獲取當前月份(0-11,0代表1月)

date.getdate(); //

獲取當前日(1-31)

date.getday(); //

獲取當前星期(0-6,0代表星期天)

date.gettime(); //

獲取當前時間(從1970.1.1開始的毫秒數)

date.gethours(); //

獲取當前小時數(0-23)

date.getminutes(); //

獲取當前分鐘數(0-59)

date.getseconds(); //

獲取當前秒數(0-59)

date.getmilliseconds(); //

獲取當前毫秒數(0-999)

date.tolocaledatestring(); (輸出結果:2021/3/18) //

獲取當前日期

date.tolocaletimestring(); (輸出結果:上午11:07:44) //

獲取當前時間

date.tolocalestring( ); (輸出結果:2021/3/18 上午11:09:02) //

獲取日期與時間

3.時間的格式化

//

對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;

}

// 對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 ino)

if (new regexp("(" + k + ")").test(fmt)) fmt = fmt.replace(regexp.$1, (regexp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" +o[k]).length)));

returnfmt;

}

呼叫:

var time1 = new date().format("yyyy-mm-dd");

var time2 = new date().format("yyyy-mm-dd hh:mm:ss");

new Date 獲取當前時間,年月日 時分秒

const d new date d.getfullyear 獲取當前年 d.getmonth 1 獲取當前月 預設0 11 d.getday 獲取週幾 d.getdate 獲取當前日 d.gethours 獲取當前小時 d.getminutes 獲取當前分 d.getseconds 獲取當前秒 d...

獲取年月日時分秒

calendar ca calendar.getinstance int year ca.get calendar.year 獲取年份 2016 system.out.println year int month ca.get calendar.month 獲取月份 10 1 system.out....

js 怎麼獲取年月日時分秒中的時分秒

var date new date 例項乙個時間物件 var year date.getfullyear 獲取系統的年 var month date.getmonth 1 獲取系統月份,由於月份是從0開始計算,所以要加1 var day date.getdate 獲取系統日 var hour dat...