Html 从 Javascript“日期”表单解析日期、月份和年份

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19597361/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 14:45:19  来源:igfitidea点击:

Parse Date, Month, and Year from Javascript "Date" form

javascripthtmlformsdate

提问by Jake Chasan

I am using the following for a user to input a date in a form:

我正在使用以下内容让用户在表单中输入日期:

<input name="name" type="date" id="id"/>

I am wondering if there is a way to parse the Day, Month, and Year from this and set them into different variables. I am trying to use only Javascript, not PHP.

我想知道是否有办法从中解析日、月和年,并将它们设置为不同的变量。我试图只使用 Javascript,而不是 PHP。

The 3 variables would be integers.

3 个变量将是整数。

Thanks.

谢谢。

回答by Brian North

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

您最好的选择,如果您接受输入并将其转换为date,无论是按部分拆分还是作为Date对象,都是Date通过将输入值传递给它来简单地构造一个新对象:

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 */ }

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 :)

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

回答by Erin Stanfill

You will want to split the value on '-', not '/'. E.g.,

您需要将值拆分为“-”,而不是“/”。例如,

$( "input" ).change(function(e) {
   var vals = e.target.value.split('-');
   var year = vals[0];
   var month = vals[1];
   var day = vals[2];
   console.info(day, month, year);
});

Here is a jsbin of a working example: http://jsbin.com/ayAjufo/2/edit

这是一个工作示例的 jsbin:http://jsbin.com/ayAjufo/2/edit

回答by Rahul Tripathi

You may try like this:-

你可以这样尝试:-

function parseDate(input) {
  var str= input.split('/');
  return new Date(str[0], str[1]-1, str[2]); 
}

str[1]-1as months start from 0.

str[1]-1因为月份是从 0 开始的。

You may also check Date.parse(string)but this implemetation dependent.

您也可以检查Date.parse(string)但这取决于实现。