我是一名PHP初学者,并且在使用php文档时遇到了困难。似乎有很多方法可以做我想做的事。
基本上我需要一个php页面来检查附加到URL的“丑陋”日期/时间变量 - 它必须将其转换为可用格式并从当前日期/时间中减去它。如果结果小于48小时,则页面应重定向到“页面A”,否则应重定向到“页面B”
这就是URL和变量的样子。
http://mysite.com/special-offer.php?date=20130527212930
$ date变量是YEAR,MONTH,DAY,HOUR,MINUTE,SECOND。我无法更改此变量的格式。
我猜PHP不能使用该字符串。所以我需要以某种方式将它拆分为PHP可以使用的日期格式。然后从当前服务器日期/时间中减去该值。
然后根据结果是否多于或小于48小时将结果放入if / else。
理论上我是对的吗?任何人都可以帮助我“练习”吗?
谢谢!
答案 0 :(得分:8)
看一下DateTime类,特别是createFromFormat
方法(php 5.3 +):
$date = DateTime::createFromFormat('YmdHis', '20130527212930');
echo $date->format('Y-m-d');
您可能需要根据前导零的使用来调整格式。
答案 1 :(得分:2)
PHP 5> = 5.3.0
$uglydate = '20130527212930';
// change ugly date to date object
$date_object = DateTime::createFromFormat('YmdHis', $uglydate);
// add 48h
$date_object->modify('+48 hours');
// current date
$now = new DateTime();
// compare dates
if( $date_object < $now ) {
echo "It was more than 48h ago";
}
答案 2 :(得分:1)
您可以使用正则表达式来读取字符串并构造有意义的值。
例如
$uglydate = "20130527212930";
preg_match("/([0-9]{4})([0-9]{2})([0-9]{2})([0-9]{2})([0-9]{2})([0-9]{2})/", $uglydate, $matches);
$datetime = $matches[1] . "-" . $matches[2] . "-" . $matches[3] . " " . $matches[4] . ":" . $matches[5] . ":" . $matches[6];
//then u can use $datetime in functions like strtotime etc
答案 3 :(得分:1)
哇!你们都有太多的时间在你的手上......很好的答案......哦,我会弹出一个完整的解决方案......
<?php
$golive = true;
if (preg_match('|^(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})|', $_GET['date'], $matches)) {
list($whole, $year, $month, $day, $hour, $minute, $second) = $matches;
// php: mktime function (using parameters derived
$timestamp = mktime($hour,$minute,$second,$month,$day,$year);
$diff = time()-$timestamp;
$diffInHours = $diff / 3600 ;
// if less, than 48
if ( $diffInHours < 48 ) {
$location = "http://bing.com";
} else {
$location = "http://google.com";
}
//
if ( $golive ) {
header("Location: ".$location);
exit();
} else {
echo "<p>You are would be sending the customer to:<br><strong>$location</strong>";
}
} else {
echo "<p>We're not sure how you got here, but... 'Welcome!'???</p>";
}
那应该做到这一点。
顺便说一句,在另一个方面,我强烈建议你回到该网址的发送方,并明确重新考虑如何做到这一点。由于这非常容易调整(URL日期=值),因此并没有真正保护任何东西,而只是将钥匙放在旁边安装在这所房子的“卫报”上的前廊上。 {sign}:)。
答案 4 :(得分:0)
假设输入的格式正确(正确的字符数和所有数字),你需要1个长度为4的子串,其余的长度为2.为简单起见,我将忽略前2个字符(来自 2013 的 20 部分与substr
$input=substr($input, 2, strlen($input));
现在我可以将字符串中的所有剩余元素视为2-char对:
$mydate=array(); //I'll store everything in here
for($i=0; $i<=strlen($input)-2; $i+=2){
$mydate[$a]=substr($input, $i, $i+2);
$a++;
}
现在我在从0到5的索引数组中有年,月,日等。对于日期差异,我将数组放入mktime:
$timestamp = mktime(mydate[3], mydate[4], mydate[5], mydate[1], mydate[2], mydate[0]);
最后比较两个时间戳:
if($old_ts - $timestamp > (60*60*48)){
//more than 48 hours
}else{ ... }