来自< input type = date>的JavaScript日期对象 [英] JavaScript date object from <input type=date>

查看:122
本文介绍了来自< input type = date>的JavaScript日期对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在focus.add_days函数中创建一个javascript日期对象,以便在元素中的给定日期添加几天。
问题是javascript对象不期望字符串Ymd所以如何创建日期对象而不将字符串Ymd解析成片段,或者是唯一的方法?

I'm trying to create a javascript date object in the focus.add_days function to add some days to the given date in a element. the problem is that the javascript object doesn't expect a string "Y-m-d" so how can I create the date object without parsing the string "Y-m-d" into pieces, or is the only way?

trigger = {
fecha_ini: function(){
    $('input[name="fecha_ini"]').on('change',function(){
      console.log('hi');
      var fecha_fin = $(':input [name=fecha_fin]');
      var min = $(this).val();
      //here is where i pass the "Y-m-d" string as the date argument
      var max = fechas.add_days(min,31*4);
      fecha_fin.attr('min',min);
      fecha_fin.attr('max',max);
      fecha_fin.val('');
    })
  }
};

fechas = {
  add_days: function addDays(date, days) {
    //here is where i use the string "Y-m-d" to create the date object, but obviusly doesnt work
    var result = new Date(date);
    result.setDate(date.getDate() + days);
    return result;
}
};

trigger.fecha_ini();


推荐答案


我该如何创建日期对象没有将字符串Ymd解析成碎片,或者是唯一的方法?

how can I create the date object without parsing the string "Y-m-d" into pieces, or is the only way?

Date.parse 将y / m / d /格式的字符串转换为日期对象,手动解析是唯一明智的方法:

While Date.parse will convert strings in y/m/d/ format to date objects, manual parsing is the only sensible way:

// s is format y-m-d
// Returns a date object for 00:00:00 local time
// on the specified date
function parseDate(s) {
  var b = s.split(/\D/);
  return new Date(b[0], --b[1], b[2]);
}

ES5指定 ISO 8601的形式应该得到所有浏览器的支持,但是不一致或所有使用的浏览器都不支持它。

ES5 specifies a form of ISO 8601 that should be supported by all browsers, however it is not supported consistently or by all browsers in use.

这篇关于来自< input type = date>的JavaScript日期对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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