2017-10-06 30 views
0

我使用this code在JavaScript中創建了一個cookie。其實,我改變了代碼一點:將GMT日期格式化爲PHP中的整數

function setCookie (name,value,days) { 
    var expires, newValue; 
    if (days) { 
     var date = new Date(); // days = 0.0006944444; // testing with one minute 
     date.setTime(date.getTime()+(days*24*60*60*1000)); 
     expires = "; expires="+date.toString(); 
     newValue = encodeURIComponent(value)+'|'+date+expires; 
    } else expires = ""; 
    document.cookie = name+"="+(newValue)+"; path=/"; 
} 

所以上面的函數發送encodeURIComponent(value)+'|'+date+expires的價值。在PHP中我可以做explode('|',$_COOKIE['my-key'])採用這樣的格式日期:

$string_time = "Fri Oct 06 2017 19:34:44 GMT 0300 (Eastern European Summer Time);

現在我需要這個字符串轉換爲整數來對PHP的time()整數格式進行比較。

執行以下操作:

$currentTime = date('YmdHis', time()); 
$expire_time = date('YmdHis', strtotime($string_time)); 

它實際上輸出這樣的:

string(14) "19700101000000" // $currentTime 
string(14) "20171006162139" // $cookie_time 

問題爲什麼$currentTime總是相同19700101000000價值?

+0

這很混亂?很明顯,你沒有從設置的cookie中獲取到期時間,但是從創建UTC日期的腳本中獲得某種方式。爲什麼不把它當作unix時間戳呢? – adeneo

+0

這是我第一次這樣做,也許你可以闡明哪些值應該設置爲UNIX時間戳? – thednp

+0

你從哪裏得到'$ string_time',你是如何得到它到服務器的? – adeneo

回答

2

只需使用Unix時間戳,而不是,因爲你不從expries設置獲取時間,但是從餅乾值

function setCookie (name,value,days) { 
    var expires, newValue; 

    if (days) { 
     var date = new Date(); 
     date.setTime(date.getTime()+(days*24*60*60*1000)); 
     expires = "; expires="+date.toUTCString(); 
     newValue = date.getTime()/1000; 
    } else { 
     expires = ""; 
    } 
    document.cookie = name+"="+(newValue)+"; path=/"; 
} 

現在你可以從time()直接進行比較的PHP unix時間戳和以秒爲單位獲得差異。

請注意,您甚至沒有使用expires變量,所以這對於cookie的有效期有多長。

+0

不是所有的日子都是24小時長的,夏令時是觀察到的,所以'(days * 24 * 60 * 60 * 1000)'可能不是正確的毫秒數:[*如何在今天的日期添加天數?* ](https://stackoverflow.com/questions/3818193/how-to-add-number-of-days-to-todays-date)。 – RobG

+0

@RobG - unix時間戳記是秒數,或者是以毫秒爲單位的javascript,因爲它不包含任何時區數據或夏令時,因此沒有任何內容可以解釋。 – adeneo

+0

該函數具有* days *參數,但使用毫秒設置該值。在當地時間,在一天的凌晨4點設置的cookie可能會在某一天的凌晨3點或5點過期(假設夏令時偏移爲1小時),即經過24小時的倍數,但以天爲單位稍微多或少。 – RobG