Comment valider si la date sélectionnée dans le sélecteur de date est le même mois que le mois en cours ou non. J'ai essayé ce qui suit mais cela ne fonctionne pas. Aidez-moi, s'il vous plaît. Merci
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js"></script> Date: <input type="text" id="thedate"> <button id="checkDate">Check this month or not</button>
$('#thedate').datepicker({ minDate: 0 }); $('#checkDate').bind('click', function() { var selectedDate = $('#thedate').datepicker('getDate'); var today = new Date(); today.setHours(0); today.setMinutes(0); today.setSeconds(0); if (Date.parse(today) == Date.parse(selectedDate)) { alert('This month'); } else { alert('Not this month'); } });
3 Réponses :
$('#thedate').datepicker({minDate:0}); $('#checkDate').bind('click', function() { var selectedDate = $('#thedate').datepicker('getDate'); var current = moment(selectedDate); if (moment().month()== current.month()) { alert('this month'); } else { alert('Not this month'); } });
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script> <link rel="stylesheet" href="http://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css"> Date: <input type="text" id="thedate"/> <button id="checkDate">Check this month or not</button>
Vous pouvez faire comme ceci utiliser la fonction month () de momentjs
$('#thedate').datepicker({minDate:0}); $('#checkDate').bind('click', function() { var selectedDate = $('#thedate').datepicker('getDate'); var current = moment(selectedDate); if (moment().month()== current.month()) { alert('this month'); } else { alert('Not this month'); } });
L'utilisation inutile de la bibliothèque doit être évitée.
new Date (). getMonth ()
new Date (). getDate ()
Mis à jour http://jsfiddle.net/9y36pq85/
$('#thedate').datepicker({minDate:0}); $('#checkDate').bind('click', function() { var selectedDate = $('#thedate').datepicker('getDate'); var d= new Date(selectedDate); var today = new Date(); if (d.getMonth() == today.getMonth()) { alert('this month'); } else { alert('Not this month'); } alert(d.getDate() == today.getDate() ?'today':'not today') });
Comment puis-je vérifier aujourd'hui ou non?
Je l'ai fait ... j'ai bien fonctionné ... Merci
Vous pouvez utiliser les méthodes getMonth
et getYear
de l'objet Date, et comparer les 2.
quelque chose comme
$('#checkDate').bind('click', function() { var selectedDate = $('#thedate').datepicker('getDate'); var today = new Date(); if (today.getYear() === selectedDate.getYear() && today.getMonth() === selectedDate.getMonth()) { alert('this month'); } else { alert('Not this month'); } });