用JSON/Javascript表示一天中时间的首选方式?
Javascript附带了Date对象,提供了几个用于处理特定时间点的实用程序 但是,如果我想表示一天中的某个时间,例如用JSON/Javascript表示一天中时间的首选方式?,javascript,json,Javascript,Json,Javascript附带了Date对象,提供了几个用于处理特定时间点的实用程序 但是,如果我想表示一天中的某个时间,例如15:00,它只是表示任何一天中的一个点,而不是与特定日期关联,该怎么办 我知道我可以使用字符串,但是对于这种数据,有没有更标准化的表示法?根据您希望的粒度,可以使用秒或毫秒。因此: var time = 900; // 900 seconds = 15:00 然后在JavaScript中,您可以在今天的日期中实例化该时间,如下所示: // get the current d
15:00
,它只是表示任何一天中的一个点,而不是与特定日期关联,该怎么办
我知道我可以使用字符串,但是对于这种数据,有没有更标准化的表示法?根据您希望的粒度,可以使用秒或毫秒。因此:
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);
回答一个更标准化的方法:大多数计算机使用,它计算从1970年1月1日UTC开始的毫秒数。但是,正如你已经说过的,日期对你来说并不重要
不管日/月/年的重要性如何,使用秒或毫秒是将数据恢复回公共JavaScript日期对象的好方法,这在应用程序级别是非常有用的
对于大量的过度考虑和语法上的甜言蜜语,你可能会觉得有用,也可能不会
var时间=900;
//获取当前日期和时间
变量日期=新日期();
//重置小时、分钟、秒、毫秒
设置时间(0,0,0,0);
//根据存储的时间进行设置
日期。设置秒(时间);
document.body.innerHTML=日期代码>我不认为有一种标准的方法来做你需要的事情,但是我会像下面的例子那样做。我们的想法是,我们将日期对象用于时间部分,而忽略其他所有内容
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.\u 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');