24

I have this sample code:

<div id="calendar"></div>
$(document).ready(function()  {
    $('#calendar').datepicker({
      dateFormat: 'yy-m-d',
      inline: true,
      onSelect: function(dateText, inst) { 
            var month = dateText.getUTCMonth();
            var day = dateText.getUTCDate();
            var year = dateText.getUTCFullYear();
            alert(day+month+year);
     } 
    });
});

When I run the code, there is an error. How to get this (date, month, year)?

1

5 Answers 5

50

You can use method getDate():

$('#calendar').datepicker({
    dateFormat: 'yy-m-d',
    inline: true,
    onSelect: function(dateText, inst) { 
        var date = $(this).datepicker('getDate'),
            day  = date.getDate(),  
            month = date.getMonth() + 1,              
            year =  date.getFullYear();
        alert(day + '-' + month + '-' + year);
    }
});

FIDDLE

3
  • 1
    why did you + 1 in date.getMonth() + 1? can you expalin? thanks Mar 9, 2016 at 7:03
  • 1
    month is 0..11, and need to be translated to 1..12
    – Atara
    Mar 22, 2016 at 13:53
  • Good work @Eli, I am searching this solution for last 15 minutes. It really helps me. But i have one confusion here day, month, year doesn't have a type. what't the type of that variables.
    – Ananda G
    Jun 19, 2016 at 7:05
12

Hi you can try viewing this jsFiddle.

I used this code:

var day = $(this).datepicker('getDate').getDate();  
var month = $(this).datepicker('getDate').getMonth();  
var year = $(this).datepicker('getDate').getYear();  

I hope this helps.

1
5

Use the javascript Date object.

$(document).ready(function()  {
    $('#calendar').datepicker({
      dateFormat: 'yy-m-d',
      inline: true,
      onSelect: function(dateText, inst) { 
            var date = new Date(dateText);
            // change date.GetDay() to date.GetDate()
            alert(date.getDate() + date.getMonth() + date.getFullYear());
     } 
    });
});
0

what about that simple way)

$(document).ready ->
 $('#datepicker').datepicker( dateFormat: 'yy-mm-dd',  onSelect: (dateStr) ->
    alert dateStr # yy-mm-dd
    #OR
    alert $("#datepicker").val(); # yy-mm-dd
0
$("#date").datepicker('getDate').getMonth() + 1; 

The month on the datepicker is 0 based (0-11), so add 1 to get the month as it appears in the date.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.