2015-12-21 22 views
1

我正在開發一個網站並使用socket.io.I進行了項目拍賣並在我的數據庫中爲每個拍賣設置了時間(unix timestamp)以結束。當用戶對該項目出價時,如果結束時間少於20秒,那麼數據庫上的時間必須更改爲剩餘20秒。在每個新的出價上,剩下的秒數將是20秒。 所以隨着中說,這是我們所擁有的:根據秒數正確顯示計時器(3:45)

  • 客戶端連接,並從服務器獲取最後的時間(服務器從數據庫中獲取它,並告訴客戶端)

  • 然後客戶端必須顯示的timeleft(當前顯示爲XXX秒)(這裏就是我需要幫助。)

  • 當用戶的出價,服務器會檢查計時器低於20秒,如果是,在服務器上的數據庫將添加UNIX_TIMESTAMP(NOW())+20

長話短說,我需要的是計算數據庫中保存的時間戳減去當前的UNIX時間戳(它已經這樣做了),然後把它變成0:00的JavaScript ... 假設數據庫時間 - 當前時間等於600秒,我應該怎麼做才能把它變成5點輸出? 謝謝!

解決方案: 我很抱歉,這是非常簡單的解決方案,我找到了一些解決方案後的一些建議。對於那些誰也面臨同樣的「問題」在這裏我找到了解決方案,它不能更簡單

var time= 300; 
var minutes = "0" + Math.floor(time/60); 
var seconds = "0" + (time - minutes * 60); 
return minutes.substr(-2) + ":" + seconds.substr(-2); 

貸誰給了在此線程這個答案的用戶:Javascript seconds to minutes and seconds

+0

您希望代碼將秒數轉換爲「分鐘:秒」格式 - 是嗎? –

+1

您可以用60來模擬秒。以分鐘爲單位的結果,其餘的以秒爲單位。確保你佔領先0。這可能是某種字符串格式,但我不知道我的頭頂。 Moment.js也會使這個過程變得非常簡單,只需要花時間,添加秒數,然後用m:ss使用其中一個格式選項。 – Sinistralis

+0

是的,請=],任何幫助將非常感謝 –

回答

1

你會以秒爲單位對秒數進行取模。以分鐘爲單位輸出結果,其餘部分以秒爲單位。確保你佔領先0。這可能是某種字符串格式,但我不知道我的頭頂。 Moment.js也會使這個過程變得非常簡單,只需要花時間,添加秒數,然後用m:ss使用其中一個格式選項。

這裏有很多關於moment.js參考的例子。這裏有一個例子:How to convert seconds to HH:mm:ss in moment.js

1

有一個簡單快捷,簡短的解決方案,以格式秒到M:SS(所以不補零分鐘你的問題問):

function fmtMSS(s){return(s-(s%=60))/60+(9<s?':':':0')+s} 

函數接受要麼一(首選) a String(2個轉換'罰分',您可以將+預先計入s的函數調用參數中,如),代表正整數秒s作爲參數。

例子:

fmtMSS( 0); // 0:00 
fmtMSS( '8'); // 0:08 
fmtMSS( 9); // 0:09 
fmtMSS( '10'); // 0:10 
fmtMSS( 59); // 0:59 
fmtMSS(+'60'); // 1:00 
fmtMSS( 69); // 1:09 
fmtMSS(3599); // 59:59 
fmtMSS('3600'); // 60:00 
fmtMSS('3661'); // 61:01 
fmtMSS(7425); // 123:45 

擊穿:

function fmtMSS(s){ // accepts seconds as Number or String. Returns m:ss 
    return(s -   // take value s and subtract (will try to convert String to Number) 
      (s %= 60) // the new value of s, now holding the remainder of s divided by 60 
         // (will also try to convert String to Number) 
     )/60 + ( // and divide the resulting Number by 60 to give minutes 
         // (can never result in a fractional value = no need for rounding) 
         // to which we concatenate a String (converts the Number to String) 
         // who's reference is chosen by the conditional operator: 
      9 < s  // if seconds is larger than 9 
      ? ':'  // then we don't need to prepend a zero 
      : ':0'  // else we do need to prepend a zero 
     ) + s ;  // and we add Number s to the string (converting it to String as well) 
} 

注:負範圍可以通過預先(0>s?(s=-s,'-'):'')+到返回式加入(實際上,(0>s?(s=-s,'-'):0)+會工作爲好)。