• 每天进步一点点!

文章分类

推荐网站

常用手册

JS日期和时间戳相互转换【原创】

<<返回

2012-09-03 12:32:22

今天遇到一个关于JS的日期和时间戳相互转换的问题,在网上找了许久略有发现,自己写了两个方法,记录一下。

 

/**
 * 返回给定时间部件的时间戳
 */
function dateToTimestamp(year, month, day, hours, minutes, seconds) {
	var date = new Date();
	year = year.length == 0 ? date.getFullYear() : year;
	month = month.length == 0 ? date.getMonth() + 1 : month + 1;
	day = day.length == 0 ? date.getDate() : day;
	hours = hours.length == 0 ? date.getHours() : hours;
	minutes = minutes.length == 0 ? date.getMinutes() : minutes;
	seconds = seconds.length == 0 ? date.getSeconds() : seconds;
	// console.log('year = ' + year + ' month = ' + month + ' day =' + day + ' hours = ' + hours + ' minutes=' + minutes + ' seconds = ' + seconds );
	return Date.UTC(year, month, day, hours, minutes, seconds) / 1000 - 3600 *  8
}

/**
 * 返回给定时间戳对应的日期格式
 */
function timestampToDate(timestamp, dateDelimiter, timeDelimiter) {
	var date = new Date();
	timestamp = timestamp == undefined ?  date.getTime() : timestamp;
	dateDelimiter = dateDelimiter == undefined ? '-' : dateDelimiter;
	timeDelimiter = timeDelimiter== undefined ?  ':' : timeDelimiter;
	
	var newDate = new Date(parseInt(timestamp) * 1000);
	var year = newDate.getFullYear();
	var month = newDate.getMonth() < 10 ? '0' + newDate.getMonth() : newDate.getMonth();
	var day = newDate.getDate() < 10 ? '0' + newDate.getDate() : newDate.getDate();
	var hours = newDate.getHours() < 10 ? '0' +newDate.getHours() : newDate.getHours();
	var minutes = newDate.getMinutes() < 10 ? '0' + newDate.getMinutes() : newDate.getMinutes();
	var seconds = newDate.getSeconds() < 10 ? '0' + newDate.getSeconds() : newDate.getSeconds();
	var fomateDateTime = year + ''+ dateDelimiter + '' + month + '' + dateDelimiter +''+ day + ' ' + hours + '' +  timeDelimiter + '' + minutes +'' + timeDelimiter + '' + seconds
	// console.log('fomateDateTime = ' +fomateDateTime);
	return fomateDateTime;
}

 

 

文章评论

  • 暂无评论

发表评论

昵称:

内容:

发表评论