将时间戳转换为数组中的实际日期/时间 - javascript

时间:2017-11-23 14:42:18

标签: javascript arrays unix-timestamp

我通过以下方式生成以下数组:

var array = upload.split("\t");

[ '1', 'test', '1511435475', '' ]
[ '1', 'test', '1511435492', '' ]
[ '1', 'test', '1511435511', '' ]
[ '1', 'test', '1511435527', '' ]
[ '2', 'test', '1511435540', '' ]
[ '2', 'test', '1511435551', '' ]
[ '2', 'test', '1511435564', '' ]

第三列是一个unix时间戳,我想用javascript将其转换为通常的日期/时间格式。如何替换该数组中的时间戳或将其放在具有通常日期/时间格式的新数组中?

3 个答案:

答案 0 :(得分:1)

您可以使用以下代码

编辑:我忘记将乘法乘以1000以从unix转换为javascript时间戳

var old_array = [ [ '1', 'test', '1511435475', '' ],[ '1', 'test', '1511435492', '' ],[ '1', 'test', '1511435511', '' ],    [ '1', 'test', '1511435527', '' ], [ '2', 'test', '1511435540', '' ],[ '2', 'test', '1511435551', '' ], [ '2', 'test', '1511435564', '' ] ]
var new_array = old_array.map(function(element){
   var temp = new Date(parseInt(element[2])*1000)
   element[2] = temp.toISOString()
   return element;
})

编辑2:由于问题存在误传,这是新的解决方案

 var array = upload.split("\t"); //I am assuming it is simply an array of string  eg. [ '1', 'test', '1511435475', '' ]
  var temp = new Date(parseInt(array [2])*1000)
       array[2] = temp.toISOString();
    // You can console array here to check 

答案 1 :(得分:0)

您可以使用momentjs及其unix()方法将unix时间戳转换为时刻对象,您可以根据需要进行格式化:tmp myapp myapp myapp_mac myapp_win64.exe

https://momentjs.com/docs/#/parsing/unix-timestamp-milliseconds/ https://momentjs.com/docs/#/displaying/format/

对于数组转换,请查看Array map()函数,该函数根据给定的数组创建一个新数组:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map

答案 2 :(得分:0)

将unix时间戳与1000相乘以获取Javascript时间戳。然后使用Date构造函数转换为所需的日期格式。



var unixTime = 1511435475;
var javascriptTime = new Date(unixTime*1000);
console.log(javascriptTime.toISOString());






var array = [ [ '1', 'test', '1511435475', '' ],[ '1', 'test', '1511435492', '' ],[ '1', 'test', '1511435511', '' ],    [ '1', 'test', '1511435527', '' ], [ '2', 'test', '1511435540', '' ],[ '2', 'test', '1511435551', '' ], [ '2', 'test', '1511435564', '' ] ]
array.forEach(function(arr){
  var timestamp = +arr[2];
  arr[2] = (new Date(timestamp * 1000)).toISOString();
})
console.log(array)




相关问题