JS控制显示时间

JavaScript010

JS控制显示时间,第1张

一般的处理方式是在前台通过JS控制,JS控制显示时间的代码如下,各种不同的显示方式:

[javascript]

function Clock() {

var date = new Date()

this.year = date.getFullYear()

this.month = date.getMonth() + 1

this.date = date.getDate()

this.day = new Array("星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六")[date.getDay()]

this.hour = date.getHours() <10 ? "0" + date.getHours() : date.getHours()

this.minute = date.getMinutes() <10 ? "0" + date.getMinutes() : date.getMinutes()

this.second = date.getSeconds() <10 ? "0" + date.getSeconds() : date.getSeconds()

this.toString = function() {

return "现在是:" + this.year + "年" + this.month + "月" + this.date + "日 " + this.hour + ":" + this.minute + ":" + this.second + " " + this.day

}//现在是<span id="clock">现在是:2013年3月6日 13:54:17 星期三</span>

[javascript]

<span></span>

this.toSimpleDate = function() {

return this.year + "-" + this.month + "-" + this.date

}//2013-03-06

this.toDetailDate = function() {

return this.year + "-" + this.month + "-" + this.date + " " + this.hour + ":" + this.minute + ":" + this.second

}//2013-03-06 13:45:43

this.display = function(ele) {

var clock = new Clock()

ele.innerHTML = clock.toString()//显示方式调用

window.setTimeout(function() {clock.display(ele)}, 1000)

}

}

本篇文章主要是对js中的时间转换—毫秒转换成日期时间的示例代码进行了介绍,需要的朋友可以过来参考下,希望对大家有所帮助

js毫秒时间转换成日期时间

代码如下:

var

oldTime

=

(new

Date("2011/11/11

20:10:10")).getTime()

//得到毫秒数

大多数是用毫秒数除以365*24*60*60&1000,这么转回去,这种方法转换太过复杂,年月日,时分秒都要不同的方法获取,而且有的年份有366天,有的365天,这么算起来就太过复杂了。

后面自己试了一个方法,居然成功了

代码如下:

var

oldTime

=

(new

Date("2011/11/11

20:10:10")).getTime()

//得到毫秒数

var

newTime

=

new

Date(oldTime)

//就得到普通的时间了

直接传入毫秒数作为参数,给Date对象就可以得到普通的时间了,然后通过getHours,getFullYear等方法获取年月日,时分秒了

<script type="text/javascript">

var date=new Date()

document.write(date.getFullYear()+'年'+date.getMonth()+1+'月'+date.getDate()+'日'

+date.getHours()+'时'+date.getMinutes()+'分'+date.getSeconds()+'秒'+' '+'星期'+date.getDay())

</script>