我们的目标是显示div来通知用户会话过期,并在会话过期之前提出延长会话。该会话通过每个页面加载事件上的后端代码进行设置,并以UTC格式保存下一个过期时间的Cookie值。
UTC时间格式示例: MM/dd/yyyy-HH:mm:ss
<div class="session-alert">
<p>Your session is going to expire in a while. To keep the current session click "OK"</p>
<button class="button button-session-ok">OK</button>
<button class="button button-session-cancel">OK</button>
</div>现在,我想使用JavaScript在下一个到期时间之前20秒显示session-alert div。如何将下一个过期时间(UTC)转换为本地时间,并从中减去20秒,并将时间间隔转换为一个间隔,以显示session-alert div?我只想使用核心的javascript或jquery,没有任何第三方的JS或插件。
var EXPIRE_COUNTDOWN_TIMER;
var nextExprireTime = new Date('05/20/2019-15:23:44');
var nextExprireTimeISO = nextExprireTime.toISOString();
var currLocalTime = new Date().toISOString();
var diff = (nextExprireTimeISO - currLocalTime) - 20 seconds;
EXPIRE_COUNTDOWN_TIMER = setInterval(function(){
$('.session-alert').show();
}, diff);发布于 2019-05-20 20:40:10
用法:toLocaleDateString
toLocaleDateString()方法返回一个字符串,该字符串对此日期的日期部分采用区分语言的表示形式。新的区域设置和选项参数允许应用程序指定应使用其格式约定的语言,并允许自定义函数的行为。在忽略区域设置和选项参数的旧实现中,所使用的区域设置和返回的字符串形式完全依赖于实现。
var options = { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' };
var today = new Date().toLocaleDateString('es-ES', options)
console.log(today)
发布于 2019-05-20 20:50:02
您可以获得UTC字符串的当前eppocTime和epocTime,然后从futureEpoch时间中减去currentEppocTime,如果显示消息的时间为20秒
var currentEppocTime = new Date().getTime();
// your UTC string should be split into year,mon,day,hours,min,sec,milisec
var futureEppocTime = new Date(year,mon,day,hours,min,sec,milisec).getTime();
if (futureEppocTime - currentEppocTime <= 20) {
// logic to show the message
}https://stackoverflow.com/questions/56220195
复制相似问题