如何从 JavaScript 中的字符串创建日期对象

发布于 2024-12-17 20:59:30 字数 247 浏览 0 评论 0原文

具有此字符串 30/11/2011。我想将其转换为日期对象。

我需要使用:

Date d = new Date(2011,11,30);   /* months 1..12? */

或者

Date d = new Date(2011,10,30);   /* months 0..11? */

Having this string 30/11/2011. I want to convert it to date object.

Do I need to use :

Date d = new Date(2011,11,30);   /* months 1..12? */

or

Date d = new Date(2011,10,30);   /* months 0..11? */

?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(8

初见 2024-12-24 20:59:30
var d = new Date(2011,10,30);

因为js中月份是从0开始索引的。

var d = new Date(2011,10,30);

as months are indexed from 0 in js.

西瓜 2024-12-24 20:59:30

你肯定想使用第二个表达式,因为 JS 中的月份是从 0 开始枚举的。

你也可以使用 Date.parse 方法,但它使用不同的日期格式:

var timestamp = Date.parse("11/30/2011");
var dateObject = new Date(timestamp);

You definitely want to use the second expression since months in JS are enumerated from 0.

Also you may use Date.parse method, but it uses different date format:

var timestamp = Date.parse("11/30/2011");
var dateObject = new Date(timestamp);
瞳孔里扚悲伤 2024-12-24 20:59:30

语法如下:

new Date(year, month [, day, hour, minute, second, millisecond ])

so

Date d = new Date(2011,10,30);

正确;天、时、分、秒、毫秒可选。

https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date

The syntax is as follows:

new Date(year, month [, day, hour, minute, second, millisecond ])

so

Date d = new Date(2011,10,30);

is correct; day, hour, minute, second, millisecond are optional.

https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date

聚集的泪 2024-12-24 20:59:30

如上所述,有多种创建日期的方法。我不会重复同样的事情。如果您正在寻找的话,这里有一个在 Java 脚本中将字符串转换为日期的小方法,

function compareDate(str1){
// str1 format should be dd/mm/yyyy. Separator can be anything e.g. / or -. It wont effect
var dt1   = parseInt(str1.substring(0,2));
var mon1  = parseInt(str1.substring(3,5));
var yr1   = parseInt(str1.substring(6,10));
var date1 = new Date(yr1, mon1-1, dt1);
return date1;
}

There are multiple methods of creating date as discussed above. I would not repeat same stuff. Here is small method to convert String to Date in Java Script if that is what you are looking for,

function compareDate(str1){
// str1 format should be dd/mm/yyyy. Separator can be anything e.g. / or -. It wont effect
var dt1   = parseInt(str1.substring(0,2));
var mon1  = parseInt(str1.substring(3,5));
var yr1   = parseInt(str1.substring(6,10));
var date1 = new Date(yr1, mon1-1, dt1);
return date1;
}
一指流沙 2024-12-24 20:59:30

非常简单:

var dt=new Date("2011/11/30");

日期应采用 ISO 格式 yyyy/MM/dd。

Very simple:

var dt=new Date("2011/11/30");

Date should be in ISO format yyyy/MM/dd.

棒棒糖 2024-12-24 20:59:30

首先像这样提取字符串

var dateString = str.match(/^(\d{2})\/(\d{2})\/(\d{4})$/);

然后,

var d = new Date( dateString[3], dateString[2]-1, dateString[1] );

First extract the string like this

var dateString = str.match(/^(\d{2})\/(\d{2})\/(\d{4})$/);

Then,

var d = new Date( dateString[3], dateString[2]-1, dateString[1] );
旧时浪漫 2024-12-24 20:59:30

始终,对于实际中有关 JavaScript 规范的任何问题,我强烈推荐 Mozilla 开发者网络,以及 他们的 JavaScript 参考

正如Date 对象的主题中关于参数变体的所述使用:

new Date(year, month, day [, hour, minute, second, millisecond ])

关于月份参数:

月份 表示月份的整数值,从 0 开始(1 月)到 11(12 月)。

显然,您应该使用月份 10 来表示 11 月。

PS:我推荐MDN的原因是它的正确性、良好的解释、示例和浏览器兼容性图表。

Always, for any issue regarding the JavaScript spec in practical, I will highly recommend the Mozilla Developer Network, and their JavaScript reference.

As it states in the topic of the Date object about the argument variant you use:

new Date(year, month, day [, hour, minute, second, millisecond ])

And about the months parameter:

month Integer value representing the month, beginning with 0 for January to 11 for December.

Clearly, then, you should use the month number 10 for November.

P.S.: The reason why I recommend the MDN is the correctness, good explanation of things, examples, and browser compatibility chart.

谁把谁当真 2024-12-24 20:59:30

我不敢相信 javascript 与解析日期不更一致。我听说没有时区时的默认值将从 UTC 更改为本地 - 希望网络做好准备;)

我更喜欢让 Javascript 在解析日期时完成繁重的工作。然而,如果能够相当透明地处理本地时区问题,那就太好了。考虑到这两件事,这里有一个函数可以在当前状态下实现这一点——当 Javascript 发生变化时,它仍然可以工作,但随后可以被删除(人们需要一点时间来赶上旧浏览器/nodejs)当然)。

function strToDate(dateStr)
{
    var dateTry = new Date(dateStr);

    if (!dateTry.getTime())
    {
        throw new Exception("Bad Date! dateStr: " + dateStr);
    }

    var tz = dateStr.trim().match(/(Z)|([+-](\d{2})\:?(\d{2}))$/);

    if (!tz)
    {
        var newTzOffset = dateTry.getTimezoneOffset() / 60;
        var newSignStr = (newTzOffset >= 0) ? '-' : '+';
        var newTz = newSignStr + ('0' + Math.abs(newTzOffset)).slice(-2) + ':00';

        dateStr = dateStr.trim() + newTz;
        dateTry = new Date(dateStr);

        if (!dateTry.getTime())
        {
            throw new Exception("Bad Date! dateStr: " + dateStr);
        }
    }

    return dateTry;
}

无论如何,我们都需要一个日期对象;所以创建一个。如果有时区,我们就完成了。否则,使用 +hh:mm 格式创建本地时区字符串(比 +hhmm 更容易被接受)。

I can't believe javascript isn't more consistent with parsing dates. And I hear the default when there is no timezone is gonna change from UTC to local -- hope the web is prepared ;)

I prefer to let Javascript do the heavy lifting when it comes to parsing dates. However it would be nice to handle the local timezone issue fairly transparently. With both of these things in mind, here is a function to do it with the current status quo -- and when Javascript changes it will still work but then can be removed (with a little time for people to catch up with older browsers/nodejs of course).

function strToDate(dateStr)
{
    var dateTry = new Date(dateStr);

    if (!dateTry.getTime())
    {
        throw new Exception("Bad Date! dateStr: " + dateStr);
    }

    var tz = dateStr.trim().match(/(Z)|([+-](\d{2})\:?(\d{2}))$/);

    if (!tz)
    {
        var newTzOffset = dateTry.getTimezoneOffset() / 60;
        var newSignStr = (newTzOffset >= 0) ? '-' : '+';
        var newTz = newSignStr + ('0' + Math.abs(newTzOffset)).slice(-2) + ':00';

        dateStr = dateStr.trim() + newTz;
        dateTry = new Date(dateStr);

        if (!dateTry.getTime())
        {
            throw new Exception("Bad Date! dateStr: " + dateStr);
        }
    }

    return dateTry;
}

We need a date object regardless; so createone. If there is a timezone, we are done. Otherwise, create a local timezone string using the +hh:mm format (more accepted than +hhmm).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文