js中怎么获取当前年份、月份和日期

JavaScript018

js中怎么获取当前年份、月份和日期,第1张

JS有自带的日期函数,获取如下:var date = new Date()var year = date.getFullYear()//获取年份var month = date.getMonth()+1//获取月份,因为是从0-11所以要+1var day = date.getDate()//获取天数var hour = date.getHours()//获取小时var minute = date.getMinutes()//获取分钟var second = date.getSeconds()//获取秒

仅针对这个问题来说,不需要那么大量的代码即可完成 方案1(适用于中国标准时间): var date = new Date(+new Date()+8*3600*1000).toISOString().replace(/T/g,' ').replace(/\.[\d]{3}Z/,'')方案2(只用于题目中所述的格式转换)

年 月 日 时 分 秒 星期 。 如果按楼主要求,星期换下就可以,也就是

var ndate = years+"年"+month+"月"+days+"日 "+hours+":"+minutes+":"+seconds+" "+week

这句 ,换成

var ndate = years+"年"+month+"月"+days+"日 "+week+" "+hours+":"+minutes+":"+seconds

<html>

<head>

<title></title>

<script language="javascript">

function getCurDate()

{

var d = new Date()

var week

switch (d.getDay()){

case 1: week="星期一"break

case 2: week="星期二"break

case 3: week="星期三"break

case 4: week="星期四"break

case 5: week="星期五"break

case 6: week="星期六"break

default: week="星期天"

}

var years = d.getYear()

var month = add_zero(d.getMonth()+1)

var days = add_zero(d.getDate())

var hours = add_zero(d.getHours())

var minutes = add_zero(d.getMinutes())

var seconds=add_zero(d.getSeconds())

var ndate = years+"年"+month+"月"+days+"日 "+hours+":"+minutes+":"+seconds+" "+week

divT.innerHTML= ndate

}

function add_zero(temp)

{

if(temp<10) return "0"+temp

else return temp

}

setInterval("getCurDate()",100)

</script>

</head>

<body>

<div id="divT"></div>

</body>

</html>