Reputation: 3
I'm really new to making dates in JavaScript, and I have a super interesting situation where I need to create a Date
object in Javascript, but all the pieces of time from an API are in different places i.e.:
"Thursday": {
"times": {
"currently_open": false,
"status": "open",
"hours": [
{
"from": "8:00am",
"to": "1:00am"
}
]
},
"date": "2018-07-12",
"rendered": "8:00am - 1:00am"
},
So somehow, I need to combine all the elements from the date
, with the hours[0].from
time. But because the actual times appear in a string as 8:00am
in this example, I'm not really sure what I have to do to convert that into a time that JavaScript can read.
This is probably pretty stupid, but what I've tried to create a new Date object by combining values from the API data like this:
openTime = new Date( Thursday.date + 'T' + Thursday.times.hours[0].from + 'Z' );
It doesn't work. lol. Does anyone have any suggestions? Basically I tried creating a string by adding all the pieces together. Any help would be amazing. Thank you.
Upvotes: 0
Views: 290
Reputation: 138267
Your time / date format is quite unique, you have to parse it manually:
const Thursday = {
"times": {
"currently_open": false,
"status": "open",
"hours": [
{
"from": "8:00am",
"to": "1:00am"
}
]
},
"date": "2018-07-12",
"rendered": "8:00am - 1:00am"
}
let [hours, minutes] = Thursday.times.hours[0].from.split(":").map(el => parseInt(el));
if (Thursday.times.hours[0].from.includes("pm"))
hours += 12;
const date = new Date(...Thursday.date.split("-").map((n, i) => n - (i === 1)), hours, minutes);
console.log(date.toString())
Upvotes: 2
Reputation: 1610
Using Moment.js:
const time = Thursday.hours[0].from;
const match = /(.*)((a|p)m)/.exec(time);
const hourMin = match[1].length === 4 ? `0${match[1]}` : match[1];
const amPm = match[2];
const openTime = moment(`${Thursday.date} ${hourMin} ${amPm}`).toDate();
Upvotes: 0