dragon19720808 2012-01-16 21:14
浏览 43
已采纳

使用JavaScript从字符串创建对象日期

In PHP if i have:

$date = "2012-01-18 16:00";

I can do:

$newDate = new DateTime($date);

In JS (jQuery) i have:

var date = "2012-01-18 16:00";

why i can't:

var newDate = new Date(date);

? This return me Invalid date.

  • 写回答

3条回答 默认 最新

  • dongyan1808 2012-01-16 21:16
    关注

    In order for that string to be parsed, you need a T between the date and the time

    var date = "2012-01-18T16:00";
    var newDate = new Date(date);
    

    so to fix your original code:

    var date = "2012-01-18 16:00";
    date = date.replace(" ", "T");
    var newDate = new Date(date);
    

    DEMO


    The Date constructor will also take a year, month, and day

    var newDate = new Date(2012, 1, 18)
    

    though to get that to work you'd have to split your string up.

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

报告相同问题?

悬赏问题

  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 shape_predictor_68_face_landmarks.dat
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料