Reputation: 1269
I use the time-slots-generator package, to display the time from 0:15 to 24:00, the problem is that this package does not provide the ability to display AM / PM and I will have to do it manually
To do this, I took some example code from StackOverflow, then changed it a little, and got the following result
let hours = 23;
let minutes = 32;
let ampm = hours >= 12 ? 'pm' : 'am';
hours = hours % 12;
hours = hours ? hours : 12; // the hour '0' should be '12'
minutes = minutes < 10 ? '0'+minutes : minutes;
const strTime = hours + ':' + minutes + ' ' + ampm;
console.log(strTime)
If you, for example, change the value of the hours to 17 and change the variable minute to 25, then you get 17:25 pm I think the logic of this function is clear to you, it checks the value and displays either AM or PM
Now I need to link this logic with my time generator, at the moment I am using a loop to display the time from 0:15 to 24:00 as I mentioned earlier, this loop looks like this
data() {
return {
timeSlots: (ts.getTimeSlots([], true, "quarter")),
}
},
formatAMPM() {
let val = Object.values(this.timeSlots);
for (let prop in val) {
console.log( val[prop]);
}
}
With this loop, I get the following result
As you already understood, now I need to do so that the times are displayed either AM or PM, maybe you can offer a simpler solution to solve this problem I will be glad about every advice, you can see this example in codesandbox
Upvotes: 1
Views: 809
Reputation: 138286
You could move that time formatting snippet into a function that could be called on each timeSlots
value:
export default {
methods: {
formatAMPM() {
const formatTime = time => {
const parts = time.split(':');
let hours = Number(parts[0]);
let minutes = Number(parts[1]);
let ampm = hours >= 12 ? 'pm' : 'am';
hours = hours % 12;
hours = hours ? hours : 12; // the hour '0' should be '12'
minutes = minutes < 10 ? '0' + minutes : minutes;
const strTime = hours + ':' + minutes + ' ' + ampm;
return strTime;
};
Object.entries(this.timeSlots).forEach(([key, time]) => {
this.timeSlots[key] = formatTime(time);
});
},
}
}
Upvotes: 2
Reputation: 46696
For dates, I recommend a more robust and flexible solution. Using date-fns' format
.
You can find an example here: https://github.com/date-fns/date-fns/issues/946#issuecomment-452766765
But using something like format(new Date(), "hh:mmaaaaa'm'")
should be good enough, and flexible on top of it. Also, unlike Momentjs, this lib is optimized and does the job well.
Upvotes: 2