我制作了一个在工作中使用的简单网络应用程序,它接受特定日期并返回 future X 天的日期。在安卓上完美运行。 Safari 似乎没有接受我能想到的最好的输入值。 Safari 只会返回未定义的 NaN。 HTML 在 W3C 验证器上进行检查。我还尝试了“use strict”和 let vs const 变量。我现在一无所知,厌倦了敲头。
<head>
<style>
body {
background-color: lightblue;
text-align: center;
}
button {
margin: 50px 0 25px;
}
</style>
</head>
<body>
<div>
<h3>Welcome to the</h3>
<h1>Ko-culator</h1>
</div>
<div>
<p>Enter last fill / pick up date:</p>
<input type="text" id="lastFillDate" placeholder="M-D-YY" style="text-align: center">
<p>Enter day supply:</p>
<input type="text" id="daySupply" placeholder="30, 60, etc" style="text-align: center">
</div>
<div>
<button type="submit" onClick="getNextFill()">Next Fill Date</button>
</div>
<div>
<p class="date-due"></p>
</div>
<script>
function getNextFill() {
const days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
const lastFillDate = new Date(document.querySelector('#lastFillDate').value);
const daySupply = document.querySelector('#daySupply').value;
const dayOfMonth = lastFillDate.getDate();
lastFillDate.setDate(dayOfMonth + Number.parseInt(daySupply));
const nextFillDate = days[lastFillDate.getDay()] + " " + (lastFillDate.getMonth() + 1) + "-" + lastFillDate.getDate() + "-" + lastFillDate.getFullYear();
document.querySelector('.date-due').innerHTML = 'Next fill is due on: <br/><br/>' + nextFillDate;
};
</script>
</body>
最佳答案
在使用如下日期字符串创建 Date 对象时,最好将日期字符串保留为 ISO 8601 格式(例如“2017-08-16”):
new Date("2017-08-16");
因为不同浏览器之间存在您意想不到的不一致。
事实上,当您尝试在 Safari 中从“8-16-17”等字符串创建 Date 对象时,您会收到无效日期。
(您还可以从 here 了解 new Date(dateString) 的工作原理)
同时,DateTime 操作为 a disaster in JavaScript ;我建议使用像 moment.js ( https://momentjs.com/ ) 这样的库,以便您可以以优雅的方式编写代码,例如:
// Create a date in specific date format
var date = moment("12-25-2017", "MM-DD-YYYY");
// Adding N days
date.add(10, 'days'); // Now it's 2018-01-04
// Output with custom format:
console.log(date.format("MM-DD-YY")); // You'll get: 01-04-18
这样您就不需要自己处理那些现有的 JavaScript 问题。
关于javascript - 简单的网络应用程序适用于 Android,但不适用于 Safari,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45705798/