2017-08-16 54 views
1

我做了一個簡單的網絡應用程序,在工作中使用,它需要一個特定的日期並在將來返回日期X天數。在Android上完美工作。 Safari似乎沒有考慮到我能想到的最佳輸入值。 Safari只會返回未定義的NaN。 HTML檢查W3C驗證器。我也嘗試'使用嚴格',讓變量與const。我現在無能爲力,厭倦了打我的頭。簡單的網絡應用程序在Android上工作,但不能在Safari瀏覽器上工作

<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> 
+0

我知道Safari的'Date.getDate()'有問題:[here](https://stackoverflow.com/questions/21883699/safari-javascript-date-nan-issue-yyyy-mm-dd- hhmmss) – TricksfortheWeb

回答

0

這是更好地保持你的日期字符串在ISO 8601的格式(例如,「2017年8月16日」),並創建一個日期字符串像Date對象:

new Date("2017-08-16"); 

因爲有跨瀏覽器的不一致性你不會期望。

實際上,當您嘗試從Safari中的字符串「8-16-17」創建Date對象時,您將得到一個無效日期

(您也可以找到如何新的日期(dateString)從here作品)

同時,日期操縱是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問題。

0

您的代碼不工作,因爲Safari對日期格式更爲嚴格。你需要輸入一個有效的格式。 要進行測試,以

const lastFillDate = new Date(Date()); 

更換

const lastFillDate = new Date(document.querySelector('#lastFillDate').value); 

,它會工作。

或輸入「2017-09-01」,也可以工作。

+0

YYYY-MM-DD格式可以工作,但當我將代碼更改爲您所建議的內容時無法使用。感謝您的幫助 – user3393940

相關問題