且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

解析日期,月份和年份从Javascript“日期”形成

更新时间:2023-01-28 23:37:23

如果您接受输入并将其转换为 date ,分为部分或作为 Date 对象通过传递输入值来简单地构造一个新的 Date 对象:

Your best option, if you're accepting input and converting it to a date, either split by part or as a Date object, is to simply construct a new Date object by passing it the input value:

var input = document.getElementById( 'id' ).value;
var d = new Date( input );

if ( !!d.valueOf() ) { // Valid date
    year = d.getFullYear();
    month = d.getMonth();
    day = d.getDate();
} else { /* Invalid date /* }

这样可以利用 Date 处理多种输入格式 - 它将需要YYYY / MM / DD,YYYY-MM-DD,MM / DD / YYYY甚至全文日期('2013年10月25日')等,而无需编写自己的解析器。有效日期然后可以通过 !! d.valueOf()轻松检查 - 如果它是好的,则为true,否则为false):

This way you can leverage Dates handling of multiple input formats - it will take YYYY/MM/DD, YYYY-MM-DD, MM/DD/YYYY, even full text dates ( 'October 25, 2013' ), etc. without having you write your own parser. Valid dates are then easily checked by !!d.valueOf() - true if it's good, false if not :)