在JSON / Javascript中表示时间的首选方式?

时间:2015-01-26 01:07:36

标签: javascript json

Javascript附带Date对象,提供了几个用于及时处理特定点的实用程序。

但是,如果我想表示一天中的某个时间,例如15:00,它只是在任何一天表示一个点,而不是与特定日期挂钩,那该怎么办?

我知道我可以使用字符串,但是这种数据的表示是否更加标准化?

2 个答案:

答案 0 :(得分:5)

根据您想要的粒度,您可以使用秒或毫秒。所以:

var time = 900; // 900 seconds = 15:00

然后在您的JavaScript中,您可以在今天的日期中实例化该时间,如下所示:

// get the current date and time
var date = new Date();

// reset the hours, mins, seconds, ms
date.setHours(0, 0, 0, 0);

// set according to the stored time
date.setSeconds(time);

回答更标准化的方法:大多数计算机使用Unix Timestamp,它计算1970年1月1日UTC时的毫秒数。但是,正如您已经说过的那样,日期对您来说并不重要。

无论日/月/年的重要性如何 - 使用秒或毫秒是将数据恢复到公共JavaScript Date对象的好方法,这在应用程序级别是非常有用的。

对于大量的过度考虑和语法糖,您可能会或可能不会发现Moment有用。



var time = 900;

// get the current date and time
var date = new Date();

// reset the hours, mins, seconds, ms
date.setHours(0, 0, 0, 0);

// set according to the stored time
date.setSeconds(time);

document.body.innerHTML = date;




答案 1 :(得分:1)

我认为没有一种标准的方法来做你需要的东西,但我会做类似下面的例子。我们的想法是,我们在时间部分使用日期对象而忽略其他所有内容。

function time(str) {
  var date = '1970-01-01 {hr:min}:00';
  var _time = new Date(date.replace('{hr:min}', str));

  return {
    getHours: function() {
      return _time.getHours();
    },

    getMinutes: function() {
      return _time.getMinutes();
    },

    getSeconds: function() {
      return _time.getSeconds();
    },

    toString: function() {
      return _time.toLocaleTimeString(); // or use `toTimeString()`
    }
  };
}

用法:

var t = time('15:30');
var t2 = time('11:45');

t.getHours(); //=> 15
t.getMinutes(); //=> 30
t.getSeconds(); //=> 0

// We're getting AM and PM for free
t.toString(); //=> "3:30:00 PM"
t2.toString(); //=> "11:45:00 AM"


更新

上面的示例没有使用原型,因此每个对象都获得这些方法的副本。如果您将拥有大量对象,那么您可能希望使用以下版本,该版本使用原型。这个版本的缺点是它暴露了this._time属性。

var time = (function() {
  var date = '1970-01-01 {hr:min}:00';
  var methods = {
    getHours: function() {
      return this._time.getHours();
    },

    getMinutes: function() {
      return this._time.getMinutes();
    },

    getSeconds: function() {
      return this._time.getSeconds();
    },

    toString: function() {
      return this._time.toLocaleTimeString(); // or use `toTimeString()`
    }
  };

  return function(str) {
    var _instance = Object.create(methods);
    _instance._time = new Date(date.replace('{hr:min}', str));

    return _instance;
  };
}());

var t = time('15:30');
var t2 = time('11:45');