0

I have the following function to filter times.

    function getFilteredTimes(time){

        const newArray = time.forEach(element => {
            const timeValue = moment.parseZone(element.startTime)

            let now = new Date(
                element.startTime,
            ).toLocaleTimeString([], {
                year: 'numeric',
                month: 'numeric',
                day: 'numeric',
                hour: 'numeric',
                minute: '2-digit',
                hour12: true,
                timeZone: 'America/New_York',
            })


            console.log( 'timevalue', new Date(element.startTime) > new Date().toLocaleString("en-US", {
                timeZone: "America/New_York"
            }))
        })

        return time.filter(item => {

            const timeValue = new Date(item.startTime); // Convert the start time to a Date object
            if (moment(item.startTime).isAfter(moment())) {
                return true;
            }else {
                return false;
            }
            // return timeValue > currentTime; // Keep only the times that are in the future
        });
    }

I tried many things. Using moment js library, using js Date() class. converting to different formate and then compare. Changing timezones.

Heres what I am getting date and times from the server

its in timezone -04:00

I am getting the current time in formate 2023-07-10T11:15:00 but server is 2023-07-10T11:15:00-04:00

How to compare this.

I wanted that only the times after the current time show not the previous ones.

  • 1
    You do not need Moment (please use Luxon or date-fns instead) or any library to compare dates. – Mr. Polywhirl Jul 10 '23 at 13:01
  • `forEach` does not return anything so `const newArray = time.forEach` makes no sense. – epascarello Jul 10 '23 at 13:05
  • https://stackoverflow.com/questions/492994/compare-two-dates-with-javascript?rq=2 – alexkarpen Jul 10 '23 at 13:12
  • Why do you always get "-04:00" from the server time? can you trim this? Then you will have a data string with the format: YYYY-MM-DDTHH:mm:ss, that could be compared with any other date in the same format. – André Jul 10 '23 at 13:37
  • 1
    Data structures like the dates you get from the server should be provided as a codeblock in the question, not a screenshot. See: [Why should I not upload images of code/data/errors?](//meta.stackoverflow.com/q/285551) – 3limin4t0r Jul 10 '23 at 13:38

1 Answers1

0

Here's my answer, hope it helps you.

const filteredTimes = time.filter(item => {
  const timeValue = moment.parseZone(item.startTime);
  return timeValue.isAfter(currentTime); // Keep only the times that are in the future
});
Diego Ammann
  • 463
  • 7