在Javascript中将包含特定格式日期的字符串解析为Date对象

发布于 2024-10-07 07:28:17 字数 169 浏览 0 评论 0原文

我正在学习 Javascript 作为一门新语言,我发现一个习惯 JS 如何处理 reg exp 和字符串操作的好方法是将包含日期的字符串解析为 Date 对象。

我有一个 "2005-05-28" 形式的字符串。将其解析为 Date 对象的最佳 Javascript 方法是什么?

I'm learning Javascript as a new language, and I figured a good way to get used to how JS handles reg exp and string manipulation is to parse a string containing a date into a Date object.

I have a string in the form "2005-05-28". What is the best Javascript-y way to parse that into a Date object?

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

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

发布评论

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

评论(2

送舟行 2024-10-14 07:28:17

非正则表达式

我不知道“最好”,但你不需要正则表达式:

var str = "2005-05-28";
var parts = str.split("-");
var dt = new Date(parseInt(parts[0], 10),
                  parseInt(parts[1], 10) - 1,
                  parseInt(parts[2], 10));

Live example

使用 String#split- 字符上拆分字符串,然后使用接受年、月(从 0 开始)和的 Date 构造函数天(从 1 开始)。

正则表达式

请注意,如果您确实想要使用正则表达式,您可以:

var str = "2005-05-28";
var parts = str.match(/^(\d{1,4})-(\d{1,2})-(\d{1,2})$/);
if (parts) {
    var dt = new Date(parseInt(parts[1], 10),
                      parseInt(parts[2], 10) - 1,
                      parseInt(parts[3], 10));
}

实例

它使用带有捕获组的正则表达式,通过 String#match 进行匹配,这会返回一个在索引 0 处完全匹配的数组,后跟捕获组。但就我的钱而言,正则表达式并没有真正给你带来任何东西。

除此之外,

如果您的日期字符串变得更复杂或可能有所不同,我会考虑将问题交给像 DateJS。但如果你的格式是那么常规,那么你就是黄金。

Non-RegExp

I don't know about "best", but you don't need a regex:

var str = "2005-05-28";
var parts = str.split("-");
var dt = new Date(parseInt(parts[0], 10),
                  parseInt(parts[1], 10) - 1,
                  parseInt(parts[2], 10));

Live example

That uses String#split to break the string on the - characters, then the Date constructor that accepts year, month (starting with 0), and day (starting with 1).

RegExp

Mind you, if you really want to use a regexp, you can:

var str = "2005-05-28";
var parts = str.match(/^(\d{1,4})-(\d{1,2})-(\d{1,2})$/);
if (parts) {
    var dt = new Date(parseInt(parts[1], 10),
                      parseInt(parts[2], 10) - 1,
                      parseInt(parts[3], 10));
}

Live example

That uses a regex with capture groups, doing the match via String#match, which returns an array with the full match at index 0 followed by the capture groups. But for my money, the regex isn't really buying you anything.

Beyond

If your date strings get more complicated or may vary, I'd look at farming the problem out to a library like DateJS. But if your format is that regular, you're golden.

甜宝宝 2024-10-14 07:28:17

该格式对于标准 JS 日期来说是可以接受的。所以你只需要做:

var dateObject = new Date("2005-05-28");

编辑:上面是错误的,TJ 是对的;我被一个懒惰的答案打败了。它甚至在 Firefox 中解析错误,将日期减一。

看到这个问题比我想象的要棘手,我仔细地做了一些测试。 IE(和其他)将接受斜杠而不是破折号(实现优先于规范)。因此,上面的内容将适用于一个简单的replace():

var dateObject = new Date(("2005-05-28").replace("-", "/"));

请注意,我还使用 MM/DD/YYYY 成功测试了这一点:

var dateObject = new Date("05/28/2005");

因此斜杠将在所有主要浏览器(包括 IE6)中进行解析。

That format is acceptable for a standard JS date. So you only have to do:

var dateObject = new Date("2005-05-28");

EDIT: The above is wrong and TJ is right; I've been busted with a lazy answer. And it even parses incorrectly in Firefox, subtracting one from the date.

Seeing that this question was trickier than I thought, I ran some tests carefully. IE (and others) will accept a slash instead of a dash (implementation trumps specification). So, the above will work with a simple replace():

var dateObject = new Date(("2005-05-28").replace("-", "/"));

Note that I also tested this successfully with MM/DD/YYYY:

var dateObject = new Date("05/28/2005");

So the slashes will parse in all major browsers (including IE6).

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