添加链接
link管理
链接快照平台
  • 输入网页链接,自动生成快照
  • 标签化管理网页链接
相关文章推荐
坚韧的李子  ·  mlab — Matplotlib ...·  2 月前    · 
急躁的书包  ·  Error[Pe167]: ...·  2 月前    · 
打酱油的油条  ·  Array to Json Object ...·  2 周前    · 
讲道义的米饭  ·  Find in a json array ...·  4 天前    · 
留胡子的杨桃  ·  今日影评 | ...·  2 年前    · 
Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Learn more about Collectives

Teams

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Learn more about Teams

I have an object with dates like this

const dateObject = {
     "BaseTransactions.maxOccurredAt": "2021-01-19T20:30:45.000",
     "BaseTransactions.minOccurredAt": "2016-12-28T12:55:37.000",
     "EmailCampaignEvents.maxOccurredAt": "2021-04-13T11:32:50.000",
     "EmailCampaignEvents.minOccurredAt": "2021-04-09T12:15:26.000",

and I've created an array from it with dates like this

const arrayOfDates: Date[] = Object.values(dateObject).map(
    (date: string | unknown) => new Date(date as string)

and I'm trying to get the min and max dates from that array like this

const minDate = new Date(Math.min.apply(null, arrayOfDates));
const maxDate = new Date(Math.max.apply(null, arrayOfDates));

but I am getting an typescript error for arrayOfDates inside of Math.min and Math.max. The error says this Argument of type 'Date[]' is not assignable to parameter of type 'number[]'. Type 'Date' is not assignable to type 'number'.ts(2345). What am I doing wrong?

Have you figured it out? I came across this as well, only difference is that I have the same code working on my backend node project, and on my create-react-app it does not. – Ron.B.I Jan 15, 2022 at 21:08

There's a much simpler solution to your issue than the answer you provided. The issue is that the Math.min and Math.max functions tries to find the smallest/biggest number, and doesn't know how to compare dates. If your array instead was an array of numbers, it would have worked. You can get a number by using Date's .getTime() which will give you the number of milliseconds since Jan 1 1970 (== UNIX time). The Date constructor also accepts that as input, and will create a Date object from that number.

I also changed some things in your code which I thought would make it cleaner.

const arrayOfDateNumbers: number[] = Object.values(dateObject)
    .map(date => 
        (new Date(date)).getTime()
const minDate = new Date(Math.min(...arrayOfDateNumbers));
const maxDate = new Date(Math.max(...arrayOfDateNumbers));
        

Thanks for contributing an answer to Stack Overflow!

  • Please be sure to answer the question. Provide details and share your research!

But avoid

  • Asking for help, clarification, or responding to other answers.
  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.