类似文章推荐:
常用 Date 类方法
var myDate = new Date();
myDate.getYear(); // 获取当前年份(2位)
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(); // 获取当前日期
myDate.toLocaleTimeString(); // 获取当前时间
myDate.toLocaleString( ); // 获取日期与时间
获取当月天数
/*获取一个月的天数 */
function getCountDays() {
var curDate = new Date();
/* 获取当前月份 */
var curMonth = curDate.getMonth();
/* 生成实际的月份: 由于curMonth会比实际月份小1, 故需加1 */
curDate.setMonth(curMonth + 1);
/* 将日期设置为0, 这里为什么要这样设置, 我不知道原因, 这是从网上学来的 */
curDate.setDate(0);
/* 返回当月的天数 */
return curDate.getDate();
}
var day = getCountDays();
通过数组来添加天数
/*紧接上一步*/
function getEvryDay() {
var dayArry=[];
for (var i = 1; i <= day; i++) {
dayArry.push(i);
}
return dayArry; // dayArry[] 中显示每一天的数字
};
获取当前时间
function getNowFormatDate() {
var date = new Date();
var seperator1 = "-";
var seperator2 = ":";
var month = date.getMonth() + 1;
var strDate = date.getDate();
if (month >= 1 && month <= 9) {
month = "0" + month;
}
if (strDate >= 0 && strDate <= 9) {
strDate = "0" + strDate;
}
var currentdate = date.getFullYear() + seperator1 + month + seperator1 + strDate
+ " " + date.getHours() + seperator2 + date.getMinutes()
+ seperator2 + date.getSeconds();
return currentdate;
}
日期大小比较
function getCfompareDate(d1, d2) {
if (d1 === '' || d2 === '') {
return false;
}
var _beginDate = new Date(d1.replace(/\-/g, "\/"));
var _endDate=new Date(d2.replace(/\-/g, "\/"));
if (d1 >= d2) {
alert("开始时间不能大于结束时间!");
return false;
}
}
getCfompareDate('2019-01-01', '2019-01-09');
js时间戳与日期格式的相互转换
- 将时间戳转换成日期格式:
function timestampToTime(timestamp) {
if (!timestamp) {
return '-';
}
let date = new Date(timestamp);
let Y = date.getFullYear() + '-';
let M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
let D = (date.getDate() < 10 ? '0' + date.getDate() : date.getDate()) + ' ';
let h = (date.getHours() < 10 ? '0' + date.getHours() : date.getHours()) + ':';
let m = (date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()) + ':';
let s = (date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds());
return Y + M + D + h + m + s;
}
timestampToTime(1403058804);
console.log(timestampToTime(1403058804)); // 2014-06-18 10:33:24
注意:如果是Unix时间戳记得乘以1000。比如:PHP函数time()获得的时间戳就要乘以1000
- 将日期格式转换成时间戳:
function timeToTimestamp(time) {
var _date = new Date(time);
// 有三种方式获取
var time1 = _date.getTime();
var time2 = _date.valueOf();
var time3 = Date.parse(_date);
return time1;
}
timeToTimestamp('2014-04-23 18:55:49:123');