[英]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.