简体   繁体   English

一天中的新JavaScript日期对象

[英]New JavaScript date object from seconds of a day

Seems simple but I can't figure it out. 看起来很简单,但我不知道。 sigh

I have 74141 as seconds in a day, how do I create a Date object from this number to represent the time in hours and seconds? 我一天中有74141秒,如何从该数字创建Date对象以小时和秒为单位表示时间? The actual date I don't care about because I'm just going to be using getHours/Seconds/Minutes to set another date which has the correct date. 我不在乎的实际日期,因为我将使用getHours / Seconds / Minutes设置另一个具有正确日期的日期。

You can use Date.prototype.setSeconds for this purpose. 为此 ,可以使用Date.prototype.setSeconds You don't really need to worry about conversion, as that is automatic: 您实际上不需要担心转换,因为这是自动的:

var date = new Date(1970, 0, 1); 
date.setSeconds(secs);

The above trick relies on the fact that the Date points exactly to midnight, so the timing you get back is precise. 上面的技巧是基于“ Date正好指向午夜的事实,因此您返回的时间很精确。 For precision reasons, I am using EPOCH, although any "exact" midnight would do. 出于精确原因,我使用EPOCH,尽管任何“精确”午夜都可以。

  1. Get the date 获取日期

      var now = new Date(); 
  2. Zero out the time-of-day fields: 将时间字段清零:

      now.setHours(0).setMinutes(0).setSeconds(0).setMilliseconds(0); 
  3. Create a new time from your time-of-day number: 从您的时间中创建一个新的时间:

      var theTime = new Date(now.getTime() + timeInSeconds * 1000); 

You could of course use a Date instance representing any other date, but it seems like using the current date would be the least weird thing to do (barring some other conditions). 您当然可以使用表示任何其他日期的Date实例,但是似乎使用当前日期是最不可思议的事情(除非有其他条件)。

edit — actually after zeroing out the time fields, you could just use .setSeconds() with your value and avoid creating a new object. 编辑 -实际上,在将时间字段清零之后,您可以将.setSeconds()与您的值一起使用,并避免创建新对象。 It's probably not a big issue one way or the other. 一种方法或另一种方法可能都不是大问题。

In addition to alex23's answer, it's enough to give 0 as date construction param. 除了alex23的答案外,足以将0用作日期构造参数。

var date = new Date(1970, 0, 1);
// same as
var date = new Date(0);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM