2013-10-09 42 views
0

我想要做的是,例如,如果當地時間是6:00PM我想顯示時間提前10分鐘,這將是6:10PM和其他時間我想去50分鐘從當前時間回來,那會是5:10PM ..什麼我迄今爲止既不因爲我只能找出如何顯示當前時間獲取2當地時間爲用戶

<script> 
var currentTime = new Date() 
var hours = currentTime.getHours() 
var minutes = currentTime.getMinutes() 


var suffix = "AM"; 
if (hours >= 12) { 
suffix = "PM"; 
hours = hours - 12; 
} 
if (hours == 0) { 
hours = 12; 
} 

if (minutes < 10) 
minutes = "0" + minutes 

document.write("<b>" + hours + ":" + minutes + " " + suffix + "</b>") 
</script> 

我怎麼回去50分鐘,其後10分鐘?

回答

1

這應該足夠了

<script> 
    var futureTime = new Date(); 
    futureTime.setMinutes(futureTime.getMinutes()+10); 

    var pastTime = new Date(); 
    pastTime.setMinutes(pastTime.getMinutes()-50); 
</script> 

然後,只需使用消遣和futureTime變量與您現有的顯示的代碼。

來源:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date

+1

Downvoted爲w3schools.com參考。使用MDN(https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date) – L0j1k

+1

更好的資源。當我交叉引用我的答案時,我添加了我在google中打的第一件事的鏈接。 –

+0

@BarryCarlyon同樣的事情與這個答案太..當我把它粘貼到我的代碼它不工作..我想如何使用它? –

0
function formatDate(d) 
{ 
    var hours = d.getHours(); 
    var minutes = d.getMinutes(); 
    var suffix = "AM"; 

    if (hours >= 12) 
    { 
     suffix = "PM"; 
     hours = hours - 12; 
    } 
    if (hours == 0) 
    { 
     hours = 12; 
    } 

    if (minutes < 10) 
    { 
     minutes = "0" + minutes; 
    } 

    return hours + ":" + minutes + " " + suffix; 
} 

var currentTime = new Date(); 

var futureTime = new Date(currentTime.getTime()); 
futureTime.setMinutes(futureTime.getMinutes() + 10); 

var pastTime = new Date(currentTime.getTime()); 
pastTime.setMinutes(pastTime.getMinutes() - 50); 

document.write("<b>" + formatDate(currentTime) + "</b>"); 
document.write("<b>" + formatDate(futureTime) + "</b>"); 
document.write("<b>" + formatDate(pastTime) + "</b>"); 
+0

我添加了這個包裹在''標籤和它的不顯示..是否有任何我做錯了? –

+0

您應該添加打印時間邏輯。我已經更新了答案,請看看。 – candyleung