检查所选日期是否小于当前日期,使用 `array.every()`。

huangapple go评论69阅读模式
英文:

Checking selected date is less than current date with array.every()

问题

I have a function where user selects dates and it gets stored in an array object.

有一个函数,用户选择日期并将其存储在一个数组对象中。

There is check to see if user does not select dates that are already passed.

有一个检查,用于确定用户是否没有选择已经过去的日期。

It should ideally allow the user to select the current date but when I do so it is not working and the check gets triggered.

理论上应该允许用户选择当前日期,但当我这样做时,它不起作用并触发了检查。

So as per the array, the dates selected by the user should be valid, instead I get the result as false.

因此,根据数组,用户选择的日期应该是有效的,但我得到的结果是false。

I only need to match dates, so time is not relevant.

我只需要匹配日期,所以时间不相关。

How do I ensure the current date is not treated as an old date.

如何确保当前日期不被视为旧日期。

英文:

I have a function where user selects dates and it gets stored in an array object.

There is check to see if user does not select dates that are already passed.

It should ideally allow user to select current date but when I do so it is not working and the check gets triggered.

datesArr = [{ date: '05/10/2023' }, { date: '05/11/2023' }];

let result = datesArr.every(({ date }) => {
  return new Date(date).toLocaleDateString() < new Date().toLocaleDateString();
});

console.log(result);

result === false ? promptMessages(`Cannot use an older date.`, 'error') : '';

So as per the array, the dates selected by the user should be valid, instead I get the result as false.

I only need to match dates, so time is not relevant.

How do I ensure the current date is not treated as an old date.

答案1

得分: 2

你可以使用 toISOString,但需要进行整合。如果我在我的时区运行脚本,那么午夜的10号变成了9号。

const now = consolidate(new Date()); 
const consolidate = date => (date.setHours(15,0,0,0), date.toISOString().split("T")[0]);  
let result = datesArr.every(({ date }) => now <= consolidate(new Date(date)));

示例:

datesArr = [{ date: '05/10/2023' }, { date: '05/11/2023' }];

const consolidate = date => (date.setHours(15,0,0,0), date.toISOString().split("T")[0]);  
const now = consolidate(new Date()); // 只需执行一次
let result = datesArr.every(({ date }) => {
  console.log(now,consolidate(new Date(date)))
  return now <= consolidate(new Date(date))
});

const message = result ? `日期在 ${now} 或将来` :  '无法使用较早的日期。错误';
console.log(message);

更多信息:Date.toISOString

英文:

You can use the toISOString but you need to consolidate. If I run the script in my timezone, the 10th at midnight becomes the 9th

const now = consolidate(new Date()); 
const consolidate = date =&gt; (date.setHours(15,0,0,0), date.toISOString().split(&quot;T&quot;)[0]);  
let result = datesArr.every(({ date }) =&gt; now &lt;= consolidate(new Date(date)));

Example

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

datesArr = [{ date: &#39;05/10/2023&#39; }, { date: &#39;05/11/2023&#39; }];

const consolidate = date =&gt; (date.setHours(15,0,0,0), date.toISOString().split(&quot;T&quot;)[0]);  
const now = consolidate(new Date()); // only need to do this once
let result = datesArr.every(({ date }) =&gt; {
console.log(now,consolidate(new Date(date)))
  return now &lt;= consolidate(new Date(date))
});

const message = result ? `Dates are on or in the future from ${now}` :  &#39;Cannot use an older date. Error&#39;;

console.log(message);

<!-- language: lang-html -->

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString

<!-- end snippet -->

答案2

得分: 1

以下是您提供的内容的中文翻译:

代码中存在的问题是 new Date(date).toLocaleDateString() &lt; new Date().toLocaleDateString() 这将会将您的日期转换为字符串,然后在那里进行比较,这是不正确的。您不能比较两个字符串以确定日期的大小。

此外,您还需要检查日期是否不是过去的日期,似乎您在使用比较运算符时出现了错误。

我采用的逻辑是:

  • 获取每个日期并创建一个日期对象。当您从日期字符串创建日期对象时,它将给出一个时间为零的日期对象。例如,new Date("05/10/2023")"Wed May 10 2023 00:00:00 GMT+0200 (中欧夏令时) {}"。获取这个特定日期的时间。
  • 类似地,获取当前日期并将小时设置为零,这将给出该日期的 getTime
  • 比较这两个时间。

JavaScript 的 getTime 会返回自纪元以来的毫秒数,纪元定义为 1970 年 1 月 1 日 UTC 时间的午夜。在我们比较的时间值中,它们都是两个具有时间 00:00:00 的特定日期。在您的情况下,比较这两个时间就足够了。

工作示例

datesArr = [{ date: "05/10/2023" }, { date: "05/11/2023" }];

let result = datesArr.every(({ date }) => new Date(date).getTime() >= new Date().setHours(0, 0, 0, 0));

console.log(result);

result === false ? console.log("不能使用旧日期。", "错误") : "";
英文:

The issues with the code you have written is new Date(date).toLocaleDateString() &lt; new Date().toLocaleDateString() this will convert your date to a sting and you are converting the strings there, that's incorrect. you cant compare two strings and see the date is greater or less

Also you have to see if the date is not a past date, sees like you have used the comparison operator incorrectly.

The logic I did is

  • Take each dates and create a date object. When you create a date object from a date string, it will give a date object with time as zeros. new Date("05/10/2023") is "Wed May 10 2023 00:00:00 GMT+0200 (Central European Summer Time) {}". Take the time of this particular date.
  • Similarly get the current date and set hours to zero, this will give you the getTime of that date.
  • Compare these two times.

JavaScript getTime will return the number of milliseconds for this date since the epoch, which is defined as the midnight at the beginning of January 1, 1970, UTC. In the time values that we are comparing its against two particular date which has time 00:00:00. Its enough to compare these two times in your case.

Working Fiddle

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

datesArr = [{ date: &quot;05/10/2023&quot; }, { date: &quot;05/11/2023&quot; }];

let result = datesArr.every(({ date }) =&gt; new Date(date).getTime() &gt;= new Date().setHours(0, 0, 0, 0));

console.log(result);

result === false ? console.log(`Cannot use an older date.`, &quot;error&quot;) : &quot;&quot;;

<!-- end snippet -->

答案3

得分: 0

Instead of comparing the result of toLocaleDateString(), I would compare the integer value using valueOf MDN page for Date.valueOf.

Your code would look like this:

const datesArr = [{ date: '05/10/2023' }, { date: '05/11/2023' }];
const now = new Date().valueOf();

const result = datesArr.every((date) => new Date(date).valueOf() < now);

console.log(result);

result === false ? promptMessages(`Cannot use an older date.`, 'error') : '';
英文:

Instead of comparing the result of toLocaleDateString(), I would compare the integer value using valueOf MDN page for Date.valueOf.

Your code would look like this:

const datesArr = [{ date: &#39;05/10/2023&#39; }, { date: &#39;05/11/2023&#39; }];
const now = new Date().valueOf();

const result = datesArr.every((date) =&gt; new Date(date).valueOf() &lt; now);

console.log(result);

result === false ? promptMessages(`Cannot use an older date.`, &#39;error&#39;) : &#39;&#39;;

huangapple
  • 本文由 发表于 2023年5月10日 16:56:40
  • 转载请务必保留本文链接:https://go.coder-hub.com/76216580.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定