dtjbcda841554 2017-08-18 17:24 采纳率: 0%
浏览 414
已采纳

使用javascript获取日期作为时间戳[重复]

This question already has an answer here:

$a = date('Y-m-d h:i:s');
echo $a;

result:

2017-08-18 09:14:02

Is there a way to get the date in the same format using javascript / jquery ?

</div>
  • 写回答

3条回答 默认 最新

  • dongmaxi6763 2017-08-18 17:33
    关注

    Here's an approach that is easy to understand for newer JavaScript developers who come from an OOP background.

    var date = new Date();
    alert(date.getFullYear() + "-" + ("0" + (date.getMonth() + 1)).slice(-2) + "-" + ("0" + date.getDate()).slice(-2) + " " + ("0" + date.getHours()).slice(-2) + ":" + ("0" + date.getMinutes()).slice(-2) + ":" + ("0" + date.getSeconds()).slice(-2));
    

    date.getMonth() + 1 because the months are 0 indexed.

    EDIT: The above solution now adds the leading zeros to getMonth() and getDay(). The slice(-2) call is a common way to getting the last two characters from the string.

    For example, if date.getMonth() returns a 9. I would get 09, and slice(-2) would return me the same 09.

    But if date.getMonth() returns a 10. I would get 010, and slice(-2) would return the last two characters again. So, 10.

    The other answers are correct, this one is just easier to understand from a beginners perspective.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化