javascript 计算两个yyyyMMddHHmmss时间戳之间的运行时间

g6ll5ycj  于 2023-04-28  发布在  Java
关注(0)|答案(3)|浏览(191)

我需要计算两个时间戳之间的时间差,格式如下:

yyyyMMddHHmmss

比如我有

var lastExecution = 20150116165100; //--- 16:51:00 16/01/2015
var currentTime =   20150116170120; //--- 17:01:20 16/01/2015

在这个特定的例子中,经过的时间是00:10:20
如何在js中计算?我是否必须将其转换为其他格式,然后才能继续?
我想要实现的是能够在变量中设置一个最小运行时间,如果lastExecution和现在之间的运行时间大于我想要启动特定函数的最小运行时间:

minTime = 00000000001000; //--- 10 minutes
var lastExecution = getLastExecutionTimestamp();
var currTime = getCurrentTimestamp();

if((currTime - lastExecution) > minTime){ //--- I need help here to calculate the elapsed time
    doSomething();
}

getLastExecutionTimestamp()getCurrentTimestamp()返回yyyyMMddHHmmss的数字时间戳,例如20150116165100
谢谢你

sqxo8psd

sqxo8psd1#

我不认为有一个真正简单和优雅的方法来做到这一点。我会从两个字符串中提取日期值,将它们转换为秒或任何浮动的值,然后减去并测量minTime,如下所示:

var lastYearSeconds = parseInt(lastExecution.substr(0,4))*31536000; //this is in seconds
var lastMonthSeconds = parseInt(lastExecution.substr(4,2))*2592000;

然后对所有其他值执行相同的操作,将它们相加,然后从currTime()解析的值中减去。
等等,忘了JavaScript中的Date()类。Yay for builtins!
基本上,只解析日期字符串中的int值,然后将它们提供给构造函数like so。然后,可以用dateObject.getTime() - otherDateObject.getTime()减去这两个日期值

8aqjt8rx

8aqjt8rx2#

试试这个,它使用你想要的格式:

function strToDate(str) {
  var year = parseInt(str.substring(0,4));
  var month = parseInt(str.substring(4,6));
  var day = parseInt(str.substring(6,8));
  var hour = parseInt(str.substring(8,10));
  var minute = parseInt(str.substring(10,12));
  var second = parseInt(str.substring(12,14));

  var date = new Date(year, month, day , hour, minute, second, 0);
  return date.getTime();
}

function timeStampToDate(timestamp) {
  var d = new Date(timestamp);

    var diffStr = ""+(d.getFullYear()-1970)+":"+d.getMonth()+":"+(d.getDate()-1)+":"+(d.getHours()-1)+":"+d.getMinutes()+":"+d.getSeconds();
    return diffStr;
}

var lastExecution = "20150116165100"; //--- 16:51:00 16/01/2015
var currentTime =   "20150116170120"; //--- 17:01:20 16/01/2015
var lastExecutionDate = strToDate(lastExecution);
var currentTimeDate = strToDate(currentTime);

var difference = (currentTimeDate - lastExecutionDate);
var diffInTime = timeStampToDate(difference);
alert("Time difference: "+diffInTime);

链接:http://jsfiddle.net/nxjk1L8s/

ltskdhd1

ltskdhd13#

使用Java 1。8、我的剧本对我有用。试试这个...

LocalDateTime now3 = LocalDateTime.now();       
System.out.println(now3);
Thread.sleep(70000);
LocalDateTime now4 = LocalDateTime.now(); 
System.out.println(now4);   
Duration duration2 = Duration.between(now3, now4);
System.out.println("duration is "+duration2);

o/p:

2023-04-27T19:14:11.968
2023-04-27T19:15:21.974
duration is PT1M10.006S

相关问题