JavaScript 中日期转换
new Date():返回当日的日期和时间
Tue Dec 01 2020 10:25:42 GMT+0800 (中国标准时间)
getDate() | 从 Date 对象返回一个月中的某一天 (1 ~ 31)。 |
---|---|
getDay() | 从 Date 对象返回一周中的某一天 (0 ~ 6)。 |
getMonth() | 从 Date 对象返回月份 (0 ~ 11)。 |
getFullYear() | 从 Date 对象以四位数字返回年份。 |
getHours() | 返回 Date 对象的小时 (0 ~ 23)。 |
getMinutes() | 返回 Date 对象的分钟 (0 ~ 59)。 |
getSeconds() | 返回 Date 对象的秒数 (0 ~ 59)。 |
getMilliseconds() | 返回 Date 对象的毫秒(0 ~ 999)。 |
getTime() | 返回 1970 年 1 月 1 日至今的毫秒数。 |
注意大部分的时间是从0开始计数的,转换时需要加1
1. Date对象转换为日期字符串
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() + 1) > 9 ? (this.getMonth() + 1).toString() : '0' + (this.getMonth() + 1));
str = str.replace(/M/g, (this.getMonth() + 1));
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
}
console.log(new Date().Format("yyyy-MM-dd hh:mm:ss"))
prototype 属性使您有能力向对象添加属性和方法。
当构造一个原型,所有的日期对象都会默认添加属性和方法。
向Date对象添加Format方法
2. 日期字符串转换为Date对象
① 方法一
var strArray=str.split(" ");
var strDate=strArray[0].split("-");
var strTime=strArray[1].split(":");
var a=new Date(strDate[0],(strDate[1]-parseInt(1)),strDate[2],strTime[0],strTime[1],strTime[2])
② 方法二
日期字符串 —> 时间戳 —> Date对象
var d= new Date(Date.parse(str.replace(/-/g,"/")));
正则表达式后面的全局标记 g 指定将该表达式应用到输入字符串中能够查找到的尽可能多的匹配。
表达式的结尾处的不区分大小写 i 标记指定不区分大小写。
3. Date对象转换为时间戳
var d = new Date();
d.getTime();
(d).valueOf();
Date.parse(d)
4. 时间戳转换为Date类型
var timestamp1 = "1172629110000"
Date d = new Date(timestamp1)
5. 日期字符串转换为时间戳
Date.parse(str.replace(/-/g,"/"));
年月日不能以横杠连接
6. 时间戳转换为日期字符串
日期字符串 —> 时间戳 —> Date对象