Home  >  Article  >  Web Front-end  >  How to get the year, month and day using js

How to get the year, month and day using js

anonymity
anonymityOriginal
2019-05-29 14:27:0215032browse

Get the year, month, day and convert the timestamp into date format

How to get the year, month and day using js

// 简单的一句代码
var date = new Date(时间戳); //获取一个时间对象
/**
 1. 下面是获取时间日期的方法,需要什么样的格式自己拼接起来就好了
 2. 更多好用的方法可以在这查到 -> http://www.w3school.com.cn/jsref/jsref_obj_date.asp
 */
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)
 
// 比如需要这样的格式 yyyy-MM-dd hh:mm:ss
var date = new Date(1398250549490);
Y = date.getFullYear() + '-';
M = (date.getMonth()+1 < 10 ? &#39;0&#39;+(date.getMonth()+1) : date.getMonth()+1) + &#39;-&#39;;
D = date.getDate() + &#39; &#39;;
h = date.getHours() + &#39;:&#39;;
m = date.getMinutes() + &#39;:&#39;;
s = date.getSeconds(); 
console.log(Y+M+D+h+m+s); 
// 输出结果:2014-04-23 18:55:49

The above is the detailed content of How to get the year, month and day using js. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:How to comment js codeNext article:How to comment js code