简体   繁体   中英

invalid date format TypeScript

I am passing in time values departureTime such as '12:00' here. Then I try to convert it into a date and perform a subtraction. However, the result of timeOfDeparture and then time till departure is invalid. How can I fix this and make everything in a uniform type?

    const timeNow = new Date();
    console.log('TIME NOW', timeNow)
    const timeOfDeparture = new Date(departureTime);
    console.log('TIME of Departure', timeOfDeparture)
    const timeTillDeparture = Math.floor((timeOfDeparture.valueOf() - timeNow.valueOf()) / 60000);
    console.log('TIME TILL DEP', timeOfDeparture)

Example console logs:

TIME NOW Tue Oct 06 2020 15:47:35 GMT+0200 (Central European Summer Time)
TIME of Departure Invalid Date
TripTimes.tsx:17 TIME TILL DEP NaN

The date object doesn't take hours as an argument. you can read more about it here

There are four ways of instantiating a date:

var d = new Date();
var d = new Date(milliseconds);
var d = new Date(dateString);
var d = new Date(year, month, day, hours, minutes, seconds, milliseconds);

If your app relies on date manipulation, or if you want to manipulate dates more easily, consider using helper libraries like momentJs .

For example, if your departure time is on the same date but just on a different hour, your departure time using momentJs will be

moment().hour(departureHour).minute(departureMinute);

When you are creating a Javascript Date object you cannot pass only hours and minutes. You can use the empty constructor or data constructor

new Date(year, month, date, hours, minutes, seconds, ms)

but the first two arguments (year and month) are obligatory at least. You could get data from timeNow and add the time values from departureTime . Example:

const timeNow = new Date();
console.log('TIME NOW', timeNow)
let departureTimeArray = departureTime.split(":");
console.log('Hour of Departure', departureTimeArray[0]);
console.log('Minutes of Departure', departureTimeArray[1]);
const timeOfDeparture = new Date(timeNow.getFullYear(), timeNow.getMonth(), timeNow.getDate(), departureTimeArray[0], departureTimeArray[1]);
console.log('TIME of Departure', timeOfDeparture);
const timeTillDeparture = Math.floor((timeOfDeparture.valueOf() - timeNow.valueOf()) / 60000);
console.log('TIME TILL DEP', timeOfDeparture)

I hope this solution helps you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM