gpt4 book ai didi

php - 将日期转换为日期时间时出错

转载 作者:行者123 更新时间:2023-11-29 01:57:53 25 4
gpt4 key购买 nike

我使用 jQuery 日期选择器在我的输入日期中选择一个日期。

我在日期选择器脚本中使用的格式是:dateFormat: 'DD, d MM, yy',

所以我在输入中得到了这个日期:“Quinta-feira, 1 Maio, 2014”(葡萄牙语日期)。

但现在我需要转换这个日期以像 mysql 中的日期时间一样保存。

如果日期是英文,我只需要使用下面的代码:

$date = DateTime::createFromFormat('l, j F, Y', $_POST['date']);
echo $date->format('Y-m-d');

但我的日期不是英语,所以我需要进行转换,我正在尝试使用下面的“convertDate”函数来完成此操作。

但是当我调用该函数时,我会像这样传递输入日期值:convertDate($_POST['date']);

我得到一个错误在非对象上调用成员函数 format() 在这一行:$day= $date->format ("l");

你看到这里有什么不对吗?因为这个功能对我来说似乎不错!

function convertDate($myDate){

$date = DateTime::createFromFormat('Ymd', $myDate);
$day = $date->format("l");
$daynum = $date->format("j");
$month = $date->format("F");
$year = $date->format("Y");

switch($day)
{
case "Segunda-Feira": $day = "Monday"; break;
case "Terça-Feira": $day = "Tuesday"; break;
case "Quarta-Feira": $day = "Wednesday"; break;
case "Quinta-Feira": $day = "Thursday"; break;
case "Sexta-Feira": $day = "Friday"; break;
case "Sábado": $day = "Saturday"; break;
case "Domingo": $day = "Sunday"; break;
default: $day = "Unknown"; break;
}

switch($month)
{
case "Janeiro": $month = "January"; break;
case "Fevereiro": $month = "February"; break;
case "Março": $month = "March"; break;
case "Abril": $month = "April"; break;
case "Maio": $month = "May"; break;
case "Junho": $month = "June"; break;
case "Julho": $month = "July"; break;
case "Agosto": $month = "August"; break;
case "Setembro": $month = "September"; break;
case "Outubro": $month = "October"; break;
case "Novembro": $month = "November"; break;
case "Dezembro": $month = "December"; break;
default: $month = "Unknown"; break;
}

echo $daynum . ", " . $month . ", " . $year;
}

尝试使用 str_ireplace:

$english = array("Segunda-Feira","Terça-Feira","Quarta-Feira","Quinta-Feira","Sexta-Feira","Sábado","Domingo");
$portuguese = array("Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday");
$result= str_ireplace ($english , $portuguese, $_POST['date']);
$date = DateTime::createFromFormat('l, j F, Y', $result);
echo $date->format('Y-m-d');

我在 echo $date->format('Y-m-d') 中遇到了同样的错误

最佳答案

您可以让 JQuery 将某种 UTC 放入隐藏的表单字段中,而不是尝试用可能的各种语言翻译日期,然后使用它:

这将返回一个 JS 日期对象:

   var currentDate = $( ".selector" ).datepicker( "getDate" );

这将从它生成一个 PHP UTC(在 JS 中是微秒...)

   var phputc = Math.ceil((currentDate.getTime()/1000));

这将以隐藏形式放入:

   $(".selector" ).change(
function()
{
var currentDate = $( ".selector" ).datepicker( "getDate" );
var phputc = Math.ceil((currentDate.getTime()/1000));
document.forms[0].nameofhiddenformfield.value = phputc;
}
);

确保你的表单中有这样的字段

   <input type="hidden" name="nameofhiddenformfield" />

然后在 PHP 端,您可以执行以下操作:

   $dateUTC = $_POST['nameofhiddenformfield'];
echo date('Y-m-d',$dateUTC);

关于php - 将日期转换为日期时间时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23409248/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com