新日期('dd/mm/yyyy')而不是newDate('mm/dd/yyyy') [英] new Date('dd/mm/yyyy') instead of newDate('mm/dd/yyyy')

查看:53
本文介绍了新日期('dd/mm/yyyy')而不是newDate('mm/dd/yyyy')的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以将 dd/mm/yyyy 格式的日期输入到 newDate 中(例如03/01/2018),以便返回对象 Wed Jan03 2018 00:00:00 GMT + 0000(格林威治标准时间){} ?

Is it possible to enter date in dd/mm/yyyy format into newDate (e.g. 03/01/2018) so that it returns object Wed Jan 03 2018 00:00:00 GMT+0000 (Greenwich Mean Time) {}?

如果我有日期 03/01/2018 ,它将返回 2018年3月1日星期四00:00:00 GMT + 0000(格林威治标准时间){} ...我没有尝试通过 mm/dd/yyyy 格式.

If I have a date 03/01/2018 it returns Thu Mar 01 2018 00:00:00 GMT+0000 (Greenwich Mean Time) {} instead... I'm not trying to pass mm/dd/yyyy format..

我看了很多关于此的文章,找不到我的问题的答案.

I've looked at plenty of posts on this and can't find an answer to my question.

推荐答案

您无法控制Date构造函数,因此需要以所需的格式为其提供日期.由于您是自己格式化日期,因此最好使用其他Date构造函数,该构造函数以year,monthIndex和day作为参数,因为在不同的浏览器和运行时中,它更具防弹性:

You have no control over the Date constructor, so you need to feed it a date in the format that it wants. Since you are formatting the date yourself, it is better to use the other Date constructor, which takes the year, monthIndex, and day as arguments, since it is more bullet-proof across different browsers and runtimes:

  function my_date(date_string) {
      var date_components = date_string.split("/");
      var day = date_components[0];
      var month = date_components[1];
      var year = date_components[2];
      return new Date(year, month - 1, day);
    }
    
    console.log(my_date("03/01/2018"));

日期的情况下,我几乎在我创建的每个JavaScript项目上都安装了 moment 库.

The case of dates one area where I install the moment library on nearly every JavaScript project I create.

注意:代码段可能会以不同的方式显示结果;检查您的控制台.

Note: Snippet may display the result differently; check your console.

这篇关于新日期('dd/mm/yyyy')而不是newDate('mm/dd/yyyy')的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆