[英]How to get the date using datepicker only month day and year
嗨,大家好,我怎樣才能僅在日期選擇器中獲取月份和年份
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>jQuery UI Datepicker - Default functionality</title>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<link rel="stylesheet" href="/resources/demos/style.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<script>
$(function() {
$("#datepicker").datepicker();
$("#datepicker").change(function() {
var date = $(this).datepicker("getDate");
$("#placeholder").text(date);
});
});
</script>
</head>
<body>
<p>Date: <input type="text" id="datepicker"/></p>
<div id="placeholder"></div>
</body>
</html>
這是上面代碼的輸出
代碼在這里
可以使用getDate
做到這一點,但我認為使用dataFormat
選項會更容易,而只需使用.val()
來.val()
吐出的值
選項1
在這里,我設置日期選擇器的格式,獲取值,然后將格式恢復為默認值。
$(function() { $("#datepicker").datepicker(); $("#datepicker").change(function() { var date = $(this).datepicker('option', 'dateFormat', 'MM dd, yy').val(); $("#placeholder").text(date); $(this).datepicker('option', 'dateFormat', 'mm/dd/yy') }); });
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css"> <script src="https://code.jquery.com/jquery-1.12.4.js"></script> <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script> <p>Date: <input type="text" id="datepicker"/></p> <div id="placeholder"></div>
選項2 (來源: 如何格式化JavaScript日期 )
這種方法只是格式化從getData
方法返回的日期。
$(function() { $("#datepicker").datepicker(); $("#datepicker").change(function() { function formatDate(date) { var monthNames = [ "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" ]; var day = ("0" + date.getDate()).slice(-2); var monthIndex = date.getMonth(); var year = date.getFullYear(); return monthNames[monthIndex] + ' ' + day + ', ' + year; } var date = formatDate(new Date($(this).datepicker("getDate"))); $("#placeholder").text(date); }); });
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css"> <script src="https://code.jquery.com/jquery-1.12.4.js"></script> <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script> <p>Date: <input type="text" id="datepicker"/></p> <div id="placeholder"></div>
閱讀該插件的文檔: http : //api.jqueryui.com/datepicker/
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.