![](/img/trans.png)
[英]How to format a date in single line in JavaScript without using any library
[英]How can i convert date in specific format in javascript? Without using any library
var options = {timeZone:'Asia/Tokyo'}; var date = new Date(1502722800000); date.toString('YYYYMMDD HH:MM'); console.log('formatted date '+date);
o/p - 2017 年 8 月 14 日星期一 20:30:00 GMT+0530 (IST)
但我想要这种日期格式的 o/p('YYYYMMDD HH:MM') 为 20170814 17:30
toString()
不接受任何参数,不能像这样使用。 我建议使用moment.js 。
例如:
var formatted = moment(1502722800000).format('YYYY/MM/DD h:mm'); console.log('formatted date '+formatted);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
如果您希望使用时区,您还可以添加Moment Timezones 。
SurisDziugas 是对的,随着时间的推移,您可以像moment(1502722800000).format('YYYYMMDD HH:MM');
一样创建和格式化您的日期moment(1502722800000).format('YYYYMMDD HH:MM');
我实际上停止使用 JS 原生Date
对象, moment
提供了更好的可能性。
不使用任何库,这可能是您的长期解决方案。
function formatDate(date) { var month = '' + (date.getMonth() + 1), day = '' + date.getDate(), year = "" + date.getFullYear(), hour = "" + date.getHours(), min = "" + date.getMinutes(); if (month.length < 2) month = '0' + month; if (day.length < 2) day = '0' + day; if (hour.length < 2) hour = '0' + hour; if (min.length < 2) min = '0' + min; return year+"/" + month +"/"+ day + " " + hour + ":" + min; } var options = { timeZone: 'Asia/Tokyo' }; var date = new Date(1502722800000); console.log(formatDate(date));
我希望这会有所帮助
问题是关于 JavaScript 中针对特定格式的解决方案,因此在没有任何其他库的情况下,直接的答案是(以Date.toISOString的垫片样式):
function pad(number) {
if (number < 10) {
return '0' + number;
}
return number;
}
function toMyDateFormat(s) {
return this.getUTCFullYear() +
pad(this.getUTCMonth() + 1) +
pad(this.getUTCDate()) +
' ' + pad(this.getUTCHours()) +
':' + pad(this.getUTCMinutes());
};
出于好奇,这是我没有任何库的最短解决方案:
function toMyDateFormat(d) {
return d.toISOString().replace(/-/g,'').replace('T', ' ').substr(0,14);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.