我正在努力获取两个日期的 console.log,以及这两天之间的日子。
这是JavaScript的部分。
var startDate;
var endDate;
$(document).ready(function() {
var j = jQuery.noConflict();
startDate = j("#startTime").datepicker({
dateFormat: 'dd.mm.yy',
onSelect: function() {
console.log("Test1");
}
});
endDate = j("#endTime").datepicker({
dateFormat: 'dd.mm.yy',
onSelect: function() {
console.log("Test2");
}
});
});
function createSpots(){
var siteUrl = '/sites/MySiteCollection';
const oneDay = 24 * 60 * 60 * 1000; // hours*minutes*seconds*milliseconds
const diffDays = Math.round(Math.abs((startDate - endDate) / oneDay));
console.log("diffDays: " + diffDays);
console.log("startDate: " + startDate);
console.log("endDate: " + endDate.dateFormat);
console.log("Spots created!");
}
这里是HTML。
<script src="/tools/Scripts/apps/Win10Rollout/AutomatedSpots.js" type="text/javascript"></script>
<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>
<link rel="stylesheet" href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css"/>
<p>Startdatum:<input id="startTime" type="text" class="hasDatepicker"/></p>
<p>Enddatum:<input id="endTime" type="text" class="hasDatepicker"/></p>
<p>Spots:
<textarea id="text" name="text" cols="35" rows="4"></textarea> </p>
<p>Anzahl Einträge je Spot:<input type="number" id="spot"/></p>
<button onclick="createSpots()" type="button" id="button">Erstellen</button>
控制台显示 startDate: [object Object]
.当我使用 startDate.getDate()
它说 Uncaught TypeError: startDate.getDate is not a function
. 使用 startDate.dateFormat
也不行。
为了计算这些日期之间的差异,我用
const oneDay = 24 * 60 * 60 * 1000; // hours*minutes*seconds*milliseconds
const diffDays = Math.round(Math.abs((startDate - endDate) / oneDay));
但这里说 diffDays: NaN
先谢谢你
在javascript中能够使用 console.log()
对象,并且要从这个对象中获取细节,你可以避免将对象连接成字符串,所以你可以使用
console.log("startDate: ", startDate);
而不是使用 console.log("startDate: " + startDate);
或者你可以通过使用 JSON.stringify
因此,它将如下。
console.log("startDate: " + JSON.stringify(startDate));
但是 startDate
变量,这是一个JQuery对象,所以如果你要记录它,它将记录html对象,所以在你的例子中,要记录在 startDate
对象,您可以使用以下方法。
console.log("startDate: " , startDate[0].value);
关于日期差的计算,你可以做以下工作。
function createSpots(){
var siteUrl = '/sites/MySiteCollection';
const startDateValue = new Date(startDate[0].value);
const endDateValue = new Date(endDate[0].value);
const oneDay = 24 * 60 * 60 * 1000; // hours*minutes*seconds*milliseconds
const diffDays = Math.round(Math.abs((startDateValue - endDateValue) / oneDay));
console.log("diffDays: " + diffDays);
console.log("startDate: " , startDateValue);
console.log("endDate: " + endDateValue);
console.log("Spots created!");
}
简单的说,你需要从用户那里得到输入的值,然后将这些值转换为日期对象,使用... new Date()
那么你就可以正常使用你的配方。