您的位置:首页 > Web前端 > JavaScript

Js获取当前日期各种操作

2013-04-24 12:36 225 查看
var myDate = new Date();
myDate.getYear();         //获取当前年份,这个会有兼容问题,现在是2013,IE输出2013,FF输出113
var myYears =(myDate.getYear()<1900)?(1900+myDate.getYear()):myDate.getYear();   //兼容的写法
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();     //获取当前日期  2013年4月24日
myDate.toLocaleString();   //获取日期与时间 2013年4月24日 12:08:10


日期时间脚本库方法

/*是否是闰年*/
Date.prototype.isLeapYear = function()
{
return (0==this.getYear()%4&&((this.getYear()%100!=0)||(this.getYear()%400==0)));
}
myDate.isLeapYear();  //false

//---------------------------------------------------
// 日期格式化
// 格式 YYYY/yyyy/YY/yy 表示年份
// MM/M 月份
// W/w 星期
// dd/DD/d/D 日期
// hh/HH/h/H 时间
// mm/m 分钟
// ss/SS/s/S 秒
//---------------------------------------------------
Date.prototype.Format = function(formatStr)
{
var str = formatStr;
var Week = ['日','一','二','三','四','五','六'];

str=str.replace(/yyyy|YYYY/,this.getFullYear());
str=str.replace(/yy|YY/,(this.getYear() % 100)>9?(this.getYear() % 100).toString():'0' + (this.getYear() % 100));

str=str.replace(/MM/,this.getMonth()>9?this.getMonth().toString():'0' + this.getMonth());
str=str.replace(/M/g,this.getMonth());

str=str.replace(/w|W/g,Week[this.getDay()]);

str=str.replace(/dd|DD/,this.getDate()>9?this.getDate().toString():'0' + this.getDate());
str=str.replace(/d|D/g,this.getDate());

str=str.replace(/hh|HH/,this.getHours()>9?this.getHours().toString():'0' + this.getHours());
str=str.replace(/h|H/g,this.getHours());
str=str.replace(/mm/,this.getMinutes()>9?this.getMinutes().toString():'0' + this.getMinutes());
str=str.replace(/m/g,this.getMinutes());

str=str.replace(/ss|SS/,this.getSeconds()>9?this.getSeconds().toString():'0' + this.getSeconds());
str=str.replace(/s|S/g,this.getSeconds());

return str;
}

//+---------------------------------------------------
//| 日期输出字符串,重载了系统的toString方法
//+--
Date.prototype.toString = function(showWeek)
{
var myDate= this;
var str = myDate.toLocaleDateString();
if (showWeek)
{
var Week = ['日','一','二','三','四','五','六'];
str += ' 星期' + Week[myDate.getDay()];
}
return str;
}
myDate.toString(true); //2013年4月24日 星期三
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: