Tengo una serie de datos que estoy mapeando donde un usuario selecciona ciertos intervalos de tiempo para reservar salas de reuniones y estoy tratando de tomar la end_date de esta reserva y calcular cuántas horas/minutos quedan antes de que finalice esta reserva.
Estoy tratando de hacer esto usando Momentjs y me pregunto cuál sería la mejor manera de hacerlo.
Mi conjunto de datos consta de algunas reservas diferentes, por lo que estoy mapeando y representando el 'Tiempo restante' en diferentes tarjetas en la interfaz de usuario.
Mi matriz se ve así:
[ { created_at: "2021-08-19T13:20:26.000000Z" end_date: "2021-08-19 17:59:50" id: 171 key_id: "30654908" } ]Y mi código actualmente se ve así:
const ActiveSession = ({navigation}) => { const {bookings} = React.useContext(StateContext); console.log(bookings); let now = moment() console.log(now); return ( <> {bookings.map((booking, index) => ( <View style={styles.subContainer} key={index}> <View style={styles.topbar}> <Image style={styles.tinyLogo} source={{uri: booking.pod.location.image}} /> <View> <Text> <Text style={{fontWeight: 'bold'}}>{booking.pod.name}</Text> </Text> <Text>{`Time left - ${moment(booking.end_date).format('H:mm')}</Text> </View> </View> </> ) }Como puede ver, tengo end_date en el formato de hora correcto, pero no estoy seguro de cómo restarle la hora actual, especialmente si es más de una hora.
Podrían ser solo unos minutos antes de que finalice la reserva o varias horas, etc. Sé que esto probablemente sea fácil, ¡pero cualquier ayuda sería muy apreciada!
Gracias por adelantado.
Tuve que asumir algunos datos y usé useState para poder volver a representar la pantalla cada segundo, pero aquí hay un ejemplo de trabajo. Déjame saber si esto es lo que estabas buscando.
import React, { useEffect, useState } from 'react'; import { StyleSheet, View, Text, TouchableOpacity } from 'react-native'; import moment from 'moment'; const formatTime = (duration) => { var hours = Math.floor(duration / 3600); var minutes = Math.floor((duration % 3600) / 60); var seconds = duration % 60; if (hours < 10) { hours = '0' + hours; } if (minutes < 10) { minutes = '0' + minutes; } if (seconds < 10) { seconds = '0' + seconds; } return hours + ':' + minutes + ':' + seconds; }; const ActiveSession = ({ navigation }) => { // const { bookings } = React.useContext(StateContext); const [bookings, setBookings] = useState([ { created_at: '2021-08-19T13:20:26.000000Z', end_date: '2021-08-19 17:59:50', id: 171, key_id: '30654908', timeLeft: moment('2021-08-19 17:59:50').diff(moment(), 'seconds'), }, { created_at: '2021-08-19T15:20:26.000000Z', end_date: '2021-08-19 18:59:50', id: 172, key_id: '30654908', timeLeft: moment('2021-08-19 18:59:50').diff(moment(), 'seconds'), }, { created_at: '2021-08-19T16:20:26.000000Z', end_date: '2021-08-19 19:59:50', id: 173, key_id: '30654908', timeLeft: moment('2021-08-19 19:59:50').diff(moment(), 'seconds'), }, ]); useEffect(() => { const timer = setInterval(() => { const newBookings = bookings.map((booking) => { return { ...booking, timeLeft: moment(booking.end_date).diff(moment(), 'seconds'), }; }); setBookings(newBookings); }, 1000); return () => { clearInterval(timer); }; }, [bookings]); return ( <> {bookings.map((booking, index) => ( <View style={styles.subContainer} key={index}> <View style={styles.topbar}> {/* <Image style={styles.tinyLogo} source={{ uri: booking.pod.location.image }} /> */} <View> <Text> {/* <Text style={{fontWeight: 'bold'}}>{booking.pod.name}</Text> */} <Text style={{ fontWeight: 'bold' }}>{booking.id}</Text> </Text> <Text>{`Time left - ${moment(booking.end_date).format( 'H:mm' )} ${formatTime(booking.timeLeft)}`}</Text> </View> </View> </View> ))} </> ); }; const styles = StyleSheet.create({}); export default ActiveSession;