【发布时间】:2020-07-27 08:40:08
【问题描述】:
我在这里有些困惑,当我被提出一种将javascript 中的日期格式转换为php 的方法时,我的日期在javascript console 结果是2020/7/1 时不正确,但在我的当我使用date('Y-m-d') 方法时,php 结果是2020-01-07。对于完整的脚本,我在下面放了更多对我的问题的理解:
我的app.js:
// get today
const today = new Date();
// get month of today
const todayInMonth = today.getMonth() + 1;
// get year of today
const todayInYear = today.getFullYear();
// count date in one month (today)
const countDayInMonth = new Date(todayInYear, todayInMonth, 0).getDate();
// get number 15 of date
let dividerOne;
countDayInMonth == '31' ? dividerOne = Math.floor(countDayInMonth / 2) : countDayInMonth == '30' ? dividerOne = countDayInMonth / 2 : countDayInMonth == '29' ? dividerOne = Math.round(countDayInMonth / 2) : dividerOne = Math.ceil(countDayInMonth / 2);
// get number 15 / 16 of date
let dividerTwo = countDayInMonth - dividerOne;
// get fist date in every month
let firstDate = new Date(todayInYear, todayInMonth - 1, 1).toLocaleDateString();
$.ajax({
url: "myController/getMyFunction",
method: "POST",
data: {firstDate: firstDate},
async: true,
dataType: "json",
success: function (data) {
console.log(data)
}
})
我的myController.php:
public function getMyFunction(Request $list) {
$firstDate = $list->firstDate;
//change '/' to '-' and read to YYYY-MM-DD
$raw_firstDate = strtr($firstDate, '/', '-');
$fix_firstDate = date('Y-m-d', strtotime($raw_firstDate));
echo json_encode($fix_firstDate);
}
如果我的解释难以理解,我深表歉意,您可以再问我一次,谢谢
【问题讨论】:
-
对我来说似乎是本地问题。如果我使用您的 php 函数并直接传递字符串,一切正常。在你操作任何东西之前,请在 php 函数中回显传递的日期,看看输出是什么。
-
结果是这样的
"7\/1\/2020" (m-d-Y) -
hm 对我来说似乎很奇怪。因为如果我没看错,日期似乎是正确的,月份/日期也可以。
-
和我一样,我对这个不太了解,因为这个问题真的让我很困惑,哦,我可以将方法更改为
date('Y-d-m'),以获取javascript的交换日期格式吗?但我担心下一步会有问题:) -
为什么要在没有时区信息的情况下将本地时间传递给服务器?我认为新的日期 (..) / 1000 时间戳更好。
标签: javascript php jquery laravel-6