Array find per day React - arrays

I have an array of schedule that I only want to show 1 data in the array depending on the day today.
{
schedule.map(s => {
let days = ['sunday', 'monday', 'tuesday', 'wednesday', 'thurdsay', 'friday', 'saturday'];
let date = new Date();
let dayIndex = date.getDay();
let dayName = days[dayIndex]
let currentSchedule = schedule.find(s => s.days == dayName)
if(currentSchedule){
return <li className="list-group-item">{currentSchedule.day}: Open: {s.open} - Close: {s.close}</li>
}
})
}
current output is
Satruday: opening: 10:00 AM PST - closing: 10:00 PM PST
Satruday: opening: 10:00 AM PST - closing: 10:00 PM PST
Satruday: opening: 10:00 AM PST - closing: 10:00 PM PST
Satruday: opening: 10:00 AM PST - closing: 10:00 PM PST
Satruday: opening: 10:00 AM PST - closing: 10:00 PM PST
Satruday: opening: 10:00 AM PST - closing: 10:00 PM PST
Satruday: opening: 10:00 AM PST - closing: 10:00 PM PST
My expected output is
for example today is saturday it will only output
Satruday: opening: 10:00 AM PST - closing: 10:00 PM PST

Map() function iterate through all elements of array. You should use filter() function instead of it. Try this code, it should work correctly.
schedule.filter(s => {
let days = ['sunday', 'monday', 'tuesday', 'wednesday', 'thurdsay', 'friday', 'saturday'];
let date = new Date();
let dayIndex = date.getDay();
let dayName = days[dayIndex];
let currentSchedule = schedule.find(s => s.days == dayName);
if(currentSchedule){
return <li className="list-group-item">{currentSchedule.day}: Open: {s.open} - Close: {s.close}</li>
}
})
But it`s also better to take out duplicate code into the definition of scheduler.
let days = ['sunday', 'monday', 'tuesday', 'wednesday', 'thurdsay', 'friday', 'saturday'];
let date = new Date();
let dayIndex = date.getDay();
let dayName = days[dayIndex];

Related

How to convert string to date in react native with moment.js?

I have this date in string, now i want to convert this with UTC using moment.js.
Wednesday, 22 September 2021, 7:00:00 am
Expected result:
Formate: DD-MMM-YYYY hh:mm a
Date: 22-Sep-2021 12:30 PM
I tried this way but not working
let dateStr = 'Wednesday, 22 September 2021, 7:00:00 am'
utcDate = moment(moment(dateStr, 'DD-MMM-YYYY hh:mm a'))
.utc()
.format('DD MMM YYYY, hh:mm A');
Also I tried this conversion with dayjs but it works well in iOS but not in Android where I get null.
utcDate = dayjs(new Date(`${dateStr} UTC`)).format(
'DD MMM YYYY, hh:mm A',
);
let me know if anyone have solution for this.
Thanks!
Try this:
let dateStr = 'Wednesday, 22 September 2021, 7:00:00 am'
const utcDate = moment(new Date(dateStr))
.utc()
.format('DD MMM YYYY, hh:mm A');
console.log(utcDate)
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js" integrity="sha512-qTXRIMyZIFb8iQcfjXWCO8+M5Tbc38Qi5WzdPOYZHIlZpzBHG3L3by84BBBOiRGiEb7KKtAOAs5qYdUiZiQNNQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
You need to remove the format from moment call.
You can do this but it is a deprecated way
let dateStr = 'Wednesday, 22 September 2021, 7:00:00 am'
// You can do this but it is deprecated way
const date = moment(dateStr)
.utc()
.format('DD MMM YYYY, hh:mm A');
console.log(date)
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>
The better solution.
let dateStr = 'Wednesday, 22 September 2021, 7:00:00 am'
const date = moment(new Date(dateStr))
.utc()
.format('DD MMM YYYY, hh:mm A');
console.log(date)
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>

convert string Time to 12 hour format in React

I have passed the showtime as a parameter and I want to convert it to 12 hour format
following is my code
componentDidMount() {
let movieInfo = queryString.parse(this.props.location.search)
console.log(movieInfo.movieid)
this.setState(movieInfo)
console.log(movieInfo.name)
movieData = movieInfo
}
my URL : is http://localhost:3000/#/seat-booking?showtimes=2130
I want to convert the "2130" into 9.30 PM. Any suggestions??
Something like this, maybe.
This assumes s is either 3 characters (930) or 4 characters (2130) but does absolutely no other validation.
function militaryTimeTo12Hour(s) {
if(s.length == 3) s = `0${s}`; // 930 -> 0930
const hour = parseInt(s.substring(0, 2), 10);
const min = parseInt(s.substring(2, 4), 10);
if(hour < 12) return `${hour % 12}:${min} AM`;
return `${hour % 12 || 12}:${min} PM`;
}
> militaryTimeTo12Hour("1230")
"12:30 PM"
> militaryTimeTo12Hour("2130")
"9:30 PM"
> militaryTimeTo12Hour("330")
"3:30 AM"
> militaryTimeTo12Hour("zquz")
"12:NaN PM"
> militaryTimeTo12Hour("3314")
"9:14 PM"
> militaryTimeTo12Hour("-799")
"-7:99 AM"
you can use moment.js
moment('2130', 'hhmm').format('h:mm A')

How can i get UTC +1 from React DatePicker?

I am using React DatePicker to get the date and time for a booking.
Everything seems to work, i get the right date and it gets sent to the database but if i select let's say 10:30 as time, what i get to the database is 9:30, because apparently UTC is being used but i am in UTC + 1.
I tried the following to convert to UTC + 1 but both methods didn't work. What else can i try?
First method:
const date1 = new Date()
const inc = 1000 * 60 * 60 // an hour
const _date = new Date(date1)
const [startDate, setStartDate] = useState(
new Date( _date.getTime() + inc )
);
Second method:
function addHoursToDate(date, hours) {
return new Date(new Date(date).setHours(date.getHours() + hours));
}
const myDate = new Date();
const [startDate, setStartDate] = useState(
addHoursToDate(myDate, 1 )
);
Try to save the date in your database as milliseconds since the Unix Epoch. In this way, you can show the right date in your client without worry about the timezone.
const yourDate = new Date();
const millisSinceUnixEpoch = yourDate.getTime();
...save on db...
...get from db...
const yourDate = new Date(millisSinceUnixEpochFromDb);

Getting only "today and yseterday" from ngx-moment in angular 9

I'm using ngx-moment pipe to display my date
it's really helpful and very useful
But I want to display the date from today and tomorrow and then the calendar date like that
if the date today then "Today and 00:00pm", it tomorrow then "Yesterday at 00:00pm",
Then if the day after tomorrow I need to show the calendar date "13/9/2020"
here is the code
date:'2020-09-13T00:00:00' ;
<div>Last updated: {{date| amTimeAgo}}</div>
I solved it
moment.updateLocale('en', {
calendar : {
lastDay : '[Yesterday] LT',
sameDay : '[Today] LT',
nextDay : 'LL',
lastWeek : 'LL',
nextWeek : 'LL',
sameElse : 'LL'
}
});

How do I sort and display a React array by year and month?

I'm fairly new to React. Basically I'm trying to display a table of receipts with the following attributes for each receipt:
{
date: '2017-07-03',
description: 'Receipt description,
amount: 300
}
I'm trying to split and order the receipts into sections as follows:
2017
July
03 Jul | Receipt Description | £300.00
------ | ------------------- | -------
01 Jul | Receipt Description | £20.00
May
03 May | Receipt Description | £300.00
------ | ------------------- | -------
01 May | Receipt Description | £20.00
2016
...
I can easily map over the objects and sort the by date but can't figure out how to split them into the year and month sections. Any guidance would be appreciated greatly!
You could do something like that:
var sorted = data.sort(function(a, b) {
return new Date(a.date) - new Date(b.date);
});
var byYearAndByMonth = {};
_.each(sorted, function(item) {
var year = item.date.substring(0,4)
var month = item.date.substring(5,7)
if (typeof byYearAndByMonth[year] === "undefined") {
byYearAndByMonth[year] = {};
}
if (typeof byYearAndByMonth[year][month] === "undefined") {
byYearAndByMonth[year][month] = [];
}
byYearAndByMonth[year][month].push(item);
});
First you sort the array, then you loop over the sorted array and build an object index by year an month.
Then to map over the object in your render() method you'll have to use Object.keys
See this jsfiddle

Resources