【问题标题】:Javascript - how to set dynamic time interval form UTC time and show contentJavascript - 如何从 UTC 时间设置动态时间间隔并显示内容
【发布时间】:2019-05-20 11:34:40
【问题描述】:

目标是显示 div 以通知用户会话到期,并在会话到期之前提供延长它。会话是通过每个页面加载事件的后端代码设置的,并保存了一个 cookie 值,下一个过期时间为 UTC。

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 秒并将时间拍成间隔以显示会话警报 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);

【问题讨论】:

  • 到目前为止你尝试了什么?
  • 不知道应该从哪里开始...

标签: javascript jquery


【解决方案1】:

使用:toLocaleDateString

toLocaleDateString() 方法返回带有语言的字符串 此日期的日期部分的敏感表示。新的 语言环境和选项参数让应用程序指定语言 应使用其格式约定并允许自定义 函数的行为。在较旧的实现中,忽略 语言环境和选项参数,使用的语言环境和形式 返回的字符串完全依赖于实现。

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

var options = { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' };
var today = new Date().toLocaleDateString('es-ES', options)
console.log(today)

【讨论】:

    【解决方案2】:

    您可以获取 UTC 字符串的当前 eppocTime 和 epocTime, 然后从 futureEpoch 时间中减去 currentEpocTime,如果它的 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
    }
    

    【讨论】:

      猜你喜欢
      • 2023-01-12
      • 1970-01-01
      • 2023-04-02
      • 2012-03-01
      • 1970-01-01
      • 2010-09-20
      • 2021-03-02
      • 2011-07-09
      • 1970-01-01
      相关资源
      最近更新 更多