我正在尝试使用逻辑来计算使用 JavaScript 和 EJS 的日期之间的周期

Im trying to use the logic to calculate periods between dates using JavaScript and EJS

我正在构建迷你 Web 应用程序,在第一个 VIEW 上我收到“开始日期”和“第二个日期”。当我单击“租用”按钮以根据给定日期计算价格时。我有 4 个使用不同价格的特殊时期。

示例: 我收到的日期在 2020 年 1 月 10 日到 13 日之间。这是第四个周期的 4 天,所以价格应该是 4*150= 600 totalPrice。如果它在这些时间段之外,则默认价格为 5。如果它在给定时间段之间,则还显示 addedDate。现在我什么也没收到,确实出了点问题,我卡住了。谢谢!

这是输入

这应该是输出

我做了那个逻辑(我希望它是正确的)。有意见可以理解

//TODO: Fire function on load and  get the start date, the end date and make the array
function getTotalPrice(arrPeriods, rentDateStart, rentDateEnd, defaultPriceOfDay) {

let totalPrice = 0;

let defaultPrice = 5;

let startOfPeriod = new Date();
let endOfPeriod = new Date(startOfPeriod.getTime() + (48 * 60 * 60 * 1000));
let month = startOfPeriod.getMonth();
let daysCountOfPeriod = [];
let day = 1000*60*60*24;
let diff = (endOfPeriod.getTime() - startOfPeriod.getTime()) / day;

//TODO: Calculate all separate days from start date to end date and put them in an array
for ( let i = 0 ; i <= diff; i++)
{
    let a = startOfPeriod.getTime() + day * i;
    let b = new Date(a);
    let c = (b.getDate() + "-" + (b.getMonth() + 1) + "-" + b.getFullYear());
    let separator = c.split('-');
    let cDate = new Date(separator[2], separator[1] - 1, separator[0]);

    daysCountOfPeriod.push(cDate)
}

//TODO: Declare the period of the different periods and the daily cost rate during this period
let firstPeriod = {startDate: new Date(2020,1-1,1), endDate: new Date(2020,1-1,4), addingDate: new Date(2019, 6, 1), pricePerDay: 2};
let secondPeriod = {startDate: new Date(2020,1-1,3), endDate: new Date(2020,1-1,8), addingDate: new Date(2019, 6, 2), pricePerDay: 60};
let thirdPeriod = {startDate: new Date(2020,1-1,5), endDate: new Date(2020,1-1,6), addingDate: new Date(2019, 6, 1), pricePerDay: 15};
let fourthPeriod = {startDate: new Date(2020,1-1,8), endDate: new Date(2020,1-1,15), addingDate: new Date(2019, 6, 15), pricePerDay: 150};

//TODO: Making an array with all the given periods
let allPeriods = [firstPeriod, secondPeriod, thirdPeriod, fourthPeriod]


//TODO: Checks how many dates there are in the array and start the loop
for (let u = 0; u < daysCountOfPeriod.length; u++) {
    for(let j = 0; j < allPeriods.length; j++) {
        if (daysCountOfPeriod[u] >= allPeriods[j].startDate && daysCountOfPeriod[u] <= allPeriods[j].endDate) {
            //TODO: Add costRate of this date to totalPrice
            totalPrice = totalPrice + allPeriods[j].pricePerDay;
        }
        else {
            totalPrice = totalPrice + defaultPrice;
        }
    }
}
//TODO: Return the total price
return totalPrice;
}

现在我想使用 EJS 将其实现到项目中。这就是我所做的。

SERVER.JS - 这是服务器逻辑

    const express = require("express");
const bodyParser = require("body-parser");
const mongoose = require("mongoose");

const app = express();

app.set("view engine", "ejs");
app.use(bodyParser.urlencoded({extended: true}));
app.use(express.static("public"))

let daysCountOfPeriod = [];

//TODO: Get methods
app.get("/result", function (req, res){
    res.render("result", {
        daysCountOfPeriod: daysCountOfPeriod
    });
});

app.get("/", function (req, res){
    res.render("dates")
})

//TODO: Post methods
app.post("/", function (req, res){

    const gettingDates = {
        startingDate: req.body.start,
        endingDate: req.body.end
    };

    daysCountOfPeriod.push(gettingDates);
    res.redirect("/result")
});

//TODO: Shows that our server is running at localhost:3000
app.listen(3000, function (){
    console.log("Server is running!")
});

这是dates.ejs基本的html:

<main class="form-signin">
    <form action="/" method="post">
        <img class="mb-4" src="images/logo.png" alt="" width=150 height="150">

        <div class="form-floating">
            <input type="date" class="form-control top" name="start" placeholder="Starting Date">
            <label for="floatingInput">Starting Date</label>
        </div>
        <div class="form-floating">
            <input type="date" class="form-control bottom" name="end" placeholder="Ending Date">
            <label for="floatingPassword">Ending Date</label>
        </div>

        <button class="w-100 btn btn-lg btn-warning" type="submit" name="button">Rent It!</button>
        <p class="mt-5 mb-3 text-muted">&copy; Bike rental company</p>
    </form>
</main>

</body>

最后 result.ejs

<body class="text-center">

<main class="form-signin">
    <section>
        <img class="mb-4" src="images/logo.png" alt="" width=150 height="150">

        <% let totalPrice = 0; %>
        <% let added = ""; %>

        <% let firstPeriod = {startDate: new Date(2020,1-1,1), endDate: new Date(2020,1-1,4), addingDate: new Date(2019, 6, 1), pricePerDay: 2}; %>
        <% let secondPeriod = {startDate: new Date(2020,1-1,3), endDate: new Date(2020,1-1,8), addingDate: new Date(2019, 6, 2), pricePerDay: 60}; %>
        <% let thirdPeriod = {startDate: new Date(2020,1-1,5), endDate: new Date(2020,1-1,6), addingDate: new Date(2019, 6, 1), pricePerDay: 15}; %>
        <% let fourthPeriod = {startDate: new Date(2020,1-1,8), endDate: new Date(2020,1-1,15), addingDate: new Date(2019, 6, 15), pricePerDay: 150}; %>

        <% let allPeriods = [firstPeriod, secondPeriod, thirdPeriod, fourthPeriod] %>

        <% for (let u = 0; u < daysCountOfPeriod.length; u++) { %>
            <% for(let j = 0; j < allPeriods.length; j++) { %>
                <%  if (daysCountOfPeriod[u] >= allPeriods[j].startDate && daysCountOfPeriod[u] <= allPeriods[j].endDate) { %>
                    //Add price of this date to totalPrice %>
                    <% totalPrice = totalPrice + allPeriods[j].pricePerDay; %>
                    <% added = allPeriods[j].addingDate; %>
                <% } %>
            <% } %>
        <% } %>
        <h1>Total Price</h1>
        <h3><%= totalPrice %>$</h3>
        <h3>Added on: <%= added %></h3>
    </section>
</main>

</body>

我想将日期“daysCountOfPeriod”放入输入中,将其放入数组,然后循环它并在给定的时间段内检查它并获得正确的结果,现在我什么也得不到。我是初学者,所以我需要一些帮助。

示例:我收到的日期在 2020 年 1 月 10 日到 13 日之间。这是第四个周期的 4 天,因此价格应为 4*150= 600 totalPrice。如果它在这些时间段之外,则默认价格为 5。如果它在给定时间段之间,则还显示 addedDate。现在我什么也没收到,确实出了点问题,我卡住了。谢谢!

如果我理解正确,你需要:

  • 使用用户定义的开始和结束日期从预定义时段列表中获取“每日价格”和“添加日期”。
  • 如果找不到匹配的时段,请改用“5”作为“每日价格”。
  • 获取开始日期和结束日期之间的天数。
  • 每天的价格乘以开始和结束日期之间的天数,得到总价。

为了尽可能减少答案,我稍微减少了您的示例并使其适用于客户端 JavaScript,但您可以轻松地将其放入 EJS。

JsFiddle Link: https://jsfiddle.net/pnjc7fsq/

// appends 00:00:00 time
var start_date = new Date((document.querySelector('#start_date').value || '') + ' 00:00:00').getTime();
// appends 24:00:00 time to target the start of the next day;
var end_date = new Date((document.querySelector('#end_date').value || '') + ' 24:00:00').getTime();
var period = periods.find(function(period) {
  return start_date >= period.startDate && end_date <= period.endDate;
});
var days = (end_date - start_date) / (1000 * 3600 * 24);
var price = period ? period.pricePerDay * days : 5 * days;
var output = 'Total Price: ' + price + ' (Price per day:' + (period && period.pricePerDay || 5) + ', Days: ' + days + ')<br>' +
              'Adding Date: ' + (period ? period.addingDate.toISOString().slice(0, 10) : '');
document.querySelector('#output').innerHTML = output;