javascript - 如何仅使用日期选择器获取日期月日和年
问题描述
大家好,我怎样才能只在日期选择器中获取月份和年份
<!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
选项会更容易,只需获取 datepicker 使用的值即可.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>
推荐阅读
- mongodb - 从 Spring Data Mongo 中删除默认本地主机
- c# - Entityframework core where条件,执行的sql字符串及其结果
- nginx-location - nginx 块的位置通配符
- typescript - 在 Jest 中为 Cloudflare Worker 实例化 FetchEvent
- ios - SWIFT 如何将数据从 SocketAPI 类发送回 ViewController?
- reactjs - 如何使用 React Navigation 将变量传递到上一个屏幕?
- javascript - 为什么我的嵌入式链接在谷歌应用引擎服务中不起作用?
- r - 如何在不使用内置函数的情况下找到第一个非 NA 向量元素?
- python - 抓取时 HTML 元素不可用
- javascript - 相对于 Yup/Formik 年份,如何要求至少今天的月份