Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript date object from <input type=date>

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();
like image 447
chagovelez1 Avatar asked May 13 '14 21:05

chagovelez1


People also ask

How can set current date in input type date in jquery?

Answers. //Get value of input text var dt = $("input[type=text]"). val(). split('-'); var date = dt[2] +"-"+ dt[1] +"-"+ dt[0];

How can set input type date in mm/dd/yyyy format using HTML?

To set and get the input type date in dd-mm-yyyy format we will use <input> type attribute. The <input> type attribute is used to define a date picker or control field. In this attribute, you can set the range from which day-month-year to which day-month-year date can be selected from.

What is the input type for date?

The <input type="date"> defines a date picker. The resulting value includes the year, month, and day.


2 Answers

Use valueAsDate:

valueAsDate
Returns: Date

Returns / Sets the value of the element, interpreted as a date, or null if conversion is not possible.

Demo:

<input type="date" id="d" value="2018-02-14">

<button onclick="console.log( document.getElementById('d').valueAsDate )">
change the date (or not) and click me
</button>
like image 131
acdcjunior Avatar answered Sep 20 '22 12:09

acdcjunior


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

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 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.

like image 21
RobG Avatar answered Sep 23 '22 12:09

RobG