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

Vy Pham
  • 1
  • 1
  • 1
  • 5

5 Answers5

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

Eli
  • 14,779
  • 5
  • 59
  • 77
  • 1
    why did you + 1 in date.getMonth() + 1? can you expalin? thanks – Francis Saul Mar 09 '16 at 07:03
  • 1
    month is 0..11, and need to be translated to 1..12 – Atara Mar 22 '16 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 '16 at 07: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.

KevinIsNowOnline
  • 773
  • 4
  • 10
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());
     } 
    });
});
viclim
  • 959
  • 8
  • 16
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
mix-fGt
  • 447
  • 5
  • 10
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.

Ben
  • 1,853
  • 19
  • 20