2011-01-06 137 views
11

如何将秒转换为javascript中的日期时间对象。JavaScript将秒转换为日期对象

例子:

1.3308313703571

1.6324722385401

这是由一系列的点,当他们发生。我理解了1.23323秒以上,但我无法更改从api中拉出的值。

+0

这些浮点数表示什么样的日期时间? – deceze 2011-01-06 04:32:18

+0

这些是从零开始的一系列秒。这只是他们发生时的一系列问题。 – jhanifen 2011-01-06 04:34:25

回答

32

你可以尝试这样的:

function toDateTime(secs) { 
    var t = new Date(1970, 0, 1); // Epoch 
    t.setSeconds(secs); 
    return t; 
} 

信息上epoch date

1

您的实例值有小数..看起来像你正试图1.something秒转换成一个日期..

同时检查正确秒,日期转换这个例子here ..你可以查看他们的js的来源。

-3
/** 
    DateTime 
    ------- 
    Author:  Jamal BOUIZEM 
    Date:  20/02/2015 
    Version: 1.0.0 
*/ 

var DateTime = (function(){ 
    return { 
     instance: function(spec){ 
      var that = { 
       h: spec.h || 0, 
       m: spec.m || 0, 
       s: spec.s || 0 
      }; 

      var d = new Date(); 
      var str = ""; 

      function __init__(h, m, s) 
      { 
       that.h = h; 
       that.m = m; 
       that.s = s; 

       d.setHours(that.h); 
       d.setMinutes(that.m); 
       d.setSeconds(that.s); 
      }; 

      that.get = function(){ 
       d.setHours(that.h); 
       d.setMinutes(that.m); 
       d.setSeconds(that.s); 
       return d; 
      }; 

      that.set = function(h, m, s){ 
       __init__(h, m, s); 
      }; 

      that.convertSecs = function(){ 
       return (that.h * 3600) + (that.m * 60) + that.s; 
      }; 

      that.secsToDate = function(seconds){ 
       var ts = seconds % 60; 
       var tm = (seconds/60) % 60; 
       var th = (seconds/3600) % 60; 
       return DateTime.instance({ h: parseInt(th), m: parseInt(tm), s: parseInt(ts) }); 
      }; 

      that.add = function(d){ 
       return that.secsToDate(that.convertSecs() + d.convertSecs()); 
      }; 

      that.subtract = function(d){ 
       return that.secsToDate(that.convertSecs() - d.convertSecs()); 
      }; 

      __init__(that.h, that.m, that.s); 
      return that; 
     } 
    } 
})(); 
0

这个问题似乎已经得到了回答,但这可能对那些试图做类似于ruby的Time.at()方法的人有帮助。

function formatDateTime(input){ 
     var epoch = new Date(0); 
     epoch.setSeconds(parseInt(input)); 
     var date = epoch.toISOString(); 
     date = date.replace('T', ' '); 
     return date.split('.')[0].split(' ')[0] + ' ' + epoch.toLocaleTimeString().split(' ')[0]; 
};