简体   繁体   中英

How to read Date from textBox, having Jquery UI DatePicker

The below Jquery UI Date Picker shows the date in correct format, but reads it wrong.

HTML:

<input type="text" id="date">
<input type="button" id="btn" value="Show"/>

JavaScript:

$('#date').datepicker({dateFormat: 'dd-mm-yy'});
$('#btn').click(function(){
  var _myDate = new Date($('#date').val());
  alert(_myDate);
});

Whats wrong? ( Jsfiddle Here )

It shows the date correct, but reads it wrong...

When I use it like this:

$('#btn').click(function(){
      var _myDate = $('#date').val();
      alert(_myDate);
 });

It's ok, but when pass it to Server side using C# as string and then converting it to DateTime it gives me error of Invalid Date when every Day is selected greater than 12 . It treats with Day as a month. And my required format of Date is dd/mm/yyyy .

maybe this is your answer

$( "#date" ).datepicker({dateFormat: 'mm-dd-yy'});
    $('#btn').click(function(){
    var _myDate = new Date($('#date').val());
    var new_date=_myDate.split('-');
    var month=new_date[0];
    var day=new_date[1];
    var year=new_date[2];
    //you have 3 data, month, day and year.

    alert(month+"/"+day+"/"+year);
    });

you can use that 3 variable day, month, year to write your programs

Change var _myDate = new Date($('#date').val() ); to var _myDate = $('#date').val());

try like this

$( "#date" ).datepicker({dateFormat: 'mm-dd-yy'});
$('#btn').click(function(){
var _myDate = new Date($('#date').val()  );
alert(_myDate);
});

DEMO

You don't need the Date type declaration - you can just do

$( "#date" ).datepicker({dateFormat: 'dd-mm-yy'});
$('#btn').click(function(){
  var _myDate = $('#date').val();
alert(_myDate);
});

Javascript is a dynamically typed language so the Date initialisation is unnecessary

Try this: it's work fine

  $('#date').datepicker({dateFormat: 'dd-mm-yy',  changeMonth:true, changeYear:true,showOn: "both",buttonImage: "",buttonImageOnly: false });

console.log($('#date').val());

My javaScript function...

convertDate = function (strDate) {
   var newDate = new Date();
   var oldDate = '';
   if (strDate.contains('/')) {
         oldDate = strDate.split('/');
      } else if (strDate.contains('-')) {
         oldDate = strDate.split('-');
      }
     //OldDate format is dd/mm/yyyy
      newDate.setDate(oldDate[0]);
      newDate.setMonth(oldDate[1] - 1);
      newDate.setYear(oldDate[2]);
      return newDate;
 }

Just parse the textbox value using parseDate with the same format you initially set up the datepicker:

console.log($.datepicker.parseDate("dd-mm-yy", $('#date').val()));

parseDate will return a Date object so that you don't need to create it manually.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM