[英]Javascript: how to convert epoch to dd-mm-yyyy
i have an epoch time: x = 1383483902000我有一个纪元时间:x = 1383483902000
I am trying to get a date like: dd-mm-yyyy and want to do this without additional library.我正在尝试获取类似日期:dd-mm-yyyy 并希望在没有其他库的情况下执行此操作。
I have tried several ways and my last method end up like:我尝试了几种方法,最后一种方法是这样的:
var date = new Date(Math.round(Number(x)));
but i get an ugly thing like: sun nov 03 2013 14:05:02 GMT+01:00但我得到一个丑陋的东西,比如: sun nov 03 2013 14:05:02 GMT+01:00
使用日期对象提取/格式化所需的部分:
var formattedDate = date.getUTCDate() + '-' + (date.getUTCMonth() + 1)+ '-' + date.getUTCFullYear()
The example below uses the UTC methods of the date object as you are dealing with epoch time (which is milliseconds since epoch in UTC): 下面的示例在处理纪元时间(自UTC中的纪元以来的毫秒数)时,使用date对象的UTC方法:
var formatDate = function formatDate(date) { // function for reusability
var d = date.getUTCDate().toString(), // getUTCDate() returns 1 - 31
m = (date.getUTCMonth() + 1).toString(), // getUTCMonth() returns 0 - 11
y = date.getUTCFullYear().toString(), // getUTCFullYear() returns a 4-digit year
formatted = '';
if (d.length === 1) { // pad to two digits if needed
d = '0' + d;
}
if (m.length === 1) { // pad to two digits if needed
m = '0' + m;
}
formatted = d + '-' + m + '-' + y; // concatenate for output
return formatted;
},
x = 1383483902000, // sample time in ms since epoch
d = new Date(x), // convert to date object
f = formatDate(d); // pass to formatDate function to get dd-mm-yyyy
console.log(f); // log output to console for testing
You can run this in the browser console as-is. 您可以按原样在浏览器控制台中运行它。
function formatDate(value: any): any{
let date = new Date(Math.round(Number(value)));
let day = ("0" + date.getDate()).slice(-2);
let month = ("0" + (date.getMonth() + 1)).slice(-2);
let formatDate = date.getFullYear()+"-"+(month)+"-"+(day) ;
return formatDate;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.