Home > Article > Web Front-end > How to convert between timestamp and date format using js
This article mainly introduces the conversion between js timestamp and date format in detail. It has certain reference value. Interested friends can refer to it.
The examples in this article share with you Android The specific code for displaying the Jiugongge picture is for your reference. The specific content is as follows
Convert timestamp to date format
var date = new Date(时间戳);获取一个时间对象。 下面是获取时间日期的方法 下面是获取时间日期的方法。 date.getFullYear();//获取完整的年份(4位,1970) date.getMonth();//获取月份(0-11,0代表1月,用的时候记得加上1) date.getDate();//获取日(1-31) date.getTime();//获取时间(从1970.1.1开始的毫秒数) date.getHours();//获取小时数(0-23) date.getMinutes();//获取分钟数(0-59) date.getSeconds();//获取秒数(0-59)
For example, I need a format like 2015-8-24_8-24-30
function formatDate(datetime) { var year = datetime.getFullYear(), month = (datetime.getMonth() + 1 < 10) ? '0' + (datetime.getMonth() + 1):datetime.getMonth() + 1, day = datetime.getDate() < 10 ? '0' + datetime.getDate() : datetime.getDate(), hour = datetime.getHours() < 10 ? '0' + datetime.getHours() : datetime.getHours(), min = datetime.getMinutes() < 10 ? '0' + datetime.getMinutes() : datetime.getMinutes(), sec = datetime.getSeconds() < 10 ? '0' + datetime.getSeconds() : datetime.getSeconds(); return year + '-' + month + '-' + day + '_' + hour + '-' + min + '-' + sec; }
Here datatime is a Date object, formatted datetime = new Date(time); time is a timestamp.
Convert date format to timestamp
var strtime = '2014-04-23 18:55:49:123'; var date = new Date(strtime); //传入一个时间格式,如果不传入就是获取现在的时间了,这样做不兼容火狐。 // 可以这样做 var arr = strtime.replace(/ |:/g, '-').split('-'); date = new Date(Date.UTC(arr[1], arr[2], arr[3], arr[4], arr[5])); //三种方式获取: time1 = date.getTime(); time2 = date.valueOf(); time3 = Date.parse(date); //三种获取的区别: 第一、第二种:会精确到毫秒 第三种:只能精确到秒,毫秒将用0来代替 比如上面代码输出的结果(一眼就能看出区别): 1398250549123 1398250549123 1398250549000
The above is what I compiled for everyone. I hope it will be helpful to everyone in the future.
Related articles:
How to use iframe elements in vue components
How to implement nav navigation bar using vue
How to scroll up the web page express
The above is the detailed content of How to convert between timestamp and date format using js. For more information, please follow other related articles on the PHP Chinese website!