1

I got an undefiend error passing my date value into formatDate function, why? How to ceate an instance in my case?

    function formatDate(date) {
        if (date) {
            var hours = date.getHours();
            var minutes = date.getMinutes();
            var format = hours < 12 ? 'am' : 'pm';
            hours = hours % 12;
            hours = hours ? hours : 12; // making 0 a 12
            minutes = minutes < 10 ? '0' + minutes : minutes;
            var time = hours + ':' + minutes + ' ' + format;
            var output = date.getMonth() + 1 + "/" + date.getDate() + "/" + date.getFullYear() + " " + time;

            console.log(output);
          alert(output);

        }
    }
    <input type="datetime-local" onblur="formatDate(this.value)" />

0

1 Answer 1

2

It's because the date that you receive in your function is a string from your input, not a Date object.

So before you call something like date.getHours(); you must need to parse your date as string to Date or you will have the Uncaught TypeError: undefined is not a function error.

Sign up to request clarification or add additional context in comments.

1 Comment

And to parse the date as a string, you would do new Date()

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.