2017-08-30 64 views
-2

如何在JavaScript中获取第二天上午8点的日期时间对象?如何获得第二天上午8点的秒数?

我尝试新的Date()

+4

你试过了什么? –

+0

如果你不使用[moment.js](https://momentjs.com/),我会建议这样做:) –

+2

“我试过新的日期()” - 嗯,'新日期()'显然无法解决你的问题。你的电脑无法读懂你的想法,但你必须告诉它你想做什么......你试着解决你的问题*是什么?或者你没有尝试过什么,只是希望别人会为你写代码? –

回答

0

效率不高,但这里有一个简单的例子。

var today = new Date(); 
 
var diff = new Date(
 
    today.getFullYear(), 
 
    today.getMonth(), 
 
    today.getDate() + 1, 
 
    8 
 
).getTime() - today.getTime(); 
 

 
console.log((diff/1000) | 0);

+0

你如何设置时区?就像,如果我在澳大利亚/布里斯班时区,并且想知道到PST或PDT上午8点的秒数,这段代码如何计算时差? –

+0

不,它会在GMT中计算出所有内容。因此,它会计算出您当前的时区(它以格林尼治标准时间获得当前时间,并计算出第二天上午8点格林威治标准时间的差异)。日期文档显示如何设置时区偏移量。 – Will

+0

我改变了代码,以提高性能和可读性。请确保它仍然按照您的预期工作。如果没有,或者如果您对更改不满意,请随时回滚编辑。 –

-1

做日期和时间操作是困难的节点。 IF你有你的机器上的PHP,我建议这个

var child_process = require('child_process'); 

var command = 'php NumSecondsTo8am.php'; 
child_process.exec(command, function(error, stdout, stderr) { 
    console.log(stdout, 'seconds'); 
}); 

然后,在同一个目录中的单独文件(我叫numSecondsTo8am.php

<?php 
# numSecondsTo8am.php 
date_default_timezone_set('America/Chicago'); 

# get the current time 
$currentTime = new DateTime(); 

# get the current time in Los Angeles, and add a day to it 
$tomorrow = new DateTime(); 
$tomorrow->setTimezone(new DateTimeZone('America/Los_Angeles')); 

$dateInterval = new DateInterval('P1D'); 
$tomorrow->add($dateInterval); 

# since we want to know about 8am, change the hour to 8am 
$tomorrow->setTime(8, 0, 0); 

# get the timestamp the future date will produce and subtract it from 
# our current timestamp 
$numSeconds = intval($tomorrow->format('U')) - 
    intval($currentTime->format('U')); 

echo "$numSeconds"; 

记住将时区字符串更改为当地时区!否则,答案将不正确。

如果您正在寻找纯节点解决方案,我还没有找到。 即使使用Moment也不会给你正确的答案

相关问题