将字符串时间戳转换为int,然后在PHP

时间:2019-04-25 08:52:59

标签: php datetime timestamp

我想知道将bigint(我正在使用mariaDB)存储在数据库中的时间戳与当前日期相比是否已经过时,有一个示例:

我已将此时间戳记存储在db = 1560499685530中,但由于某种原因,当我从数据库中获取它时,它是一个字符串,因此在尝试设置其时间戳记(setTimestamp($ timestamp))时出现此错误< / p>

  

DateTime :: setTimestamp()期望参数1为整数,字符串   给

我尝试使用intval,但我的时间戳似乎太长而无法成为int,因为当我使用inval时,它返回的另一个int小于我的int,我猜这就是PHP int上限

我希望我的PHP打印出来,如果它已经是旧日期了,并与当前日期进行比较并编写此代码

$qBloqueo = mysqli_query($conn, "SELECT * FROM dates WHERE idUsuario = '$idUsuario'") or die(mysqli_error($conn));

$timestamp = mysqli_fetch_assoc($qBloqueo);
$timestamp = intval($timestamp['timestamp']); // Getting the timestamp from my db which is a string, still dunno why, in my db it's a bigint

$today = new DateTime();
$expireDate = new DateTime();
$expireDate->setTimestamp($timestamp);

if($today->format("Y-m-d") > $expireDate->format("Y-m-d")) { 
    print('Old date ^u^');
} else {
    print('Not yet');
}

如何在没有int的情况下使用时间戳创建日期obj,或者有什么方法将其从字符串转换为int?我只想根据字符串时间戳记创建一个日期,以便可以将其与当前日期进行比较

2 个答案:

答案 0 :(得分:-1)

如果只考虑类型,则可以键入强制转换变量,例如:

SimpleStrategy

答案 1 :(得分:-1)

如果您要查找两次之间的差异

<?php 

$time1 = new DateTime('09:00:59');
$time2 = new DateTime('09:01:00');
$interval = $time1->diff($time2);
echo $interval->format('%s second(s)');
?> 

Output :
1 second(s) 

现在可以找到两个时间戳之间的差异

/* PHP/5.5.8 and later */
$start = new DateTimeImmutable('2016-04-20 00:37:15');
$end = $start->modify('+7 days');
$diff = $end->diff($start);
print_r($diff);

Output : 
DateInterval Object ( [y] => 0 [m] => 0 [d] => 7 [h] => 0 [i] => 0 [s] => 0 [f] => 0 [weekday] => 0 [weekday_behavior] => 0 [first_last_day_of] => 0 [invert] => 1 [days] => 7 [special_type] => 0 [special_amount] => 0 [have_weekday_relative] => 0 [have_special_relative] => 0 ) 

要将日期时间戳转换为毫秒

$yourdate = '2016-03-22 14:30';
$stamp = strtotime($yourdate); // get unix timestamp
$time_in_ms = $stamp*1000;
print_r($time_in_ms);

Output : 
1458657000000

您可以将两个时间都转换为毫秒,然后找出哪个更大。 我希望这会有所帮助