Subtract 2 times in react-native - react-native

I want to subtract two times and check if check_in time > 12Hr then navigate to checkin screen. This is my code snippet
class SplashView extends Component {
componentDidMount() {
const curr_time = moment().format('hh:mm:ss');
const checkin_time = moment(this.props.datetime).format('hh:mm:ss');
// const diff = moment.duration(checkin_time.diff(curr_time));
console.log("TIME&&&&&&&&", curr_time, checkin_time);
setTimeout(() => {
if (this.props.employee_id === null) {
this.props.navigation.navigate('Login');
} else {
this.props.navigation.navigate('Checkin');
}
}, 1000)
}
render() {
return ();
}
}
I'm using moment.js and the value of this.props.datetime is '2019-02-04 14:52:01'. This is my checkin time.

You can get the difference in hours like this:
const diff = moment.duration(checkin_time.diff(curr_time)).as('hours');
Or you can just use moment's diff function
const diff = checkin_time.diff(curr_time, 'hours')
and then compare if (diff > 12) { ... }

Related

Video Element - Skip Multiple Sections [duplicate]

I have a requirement where I need to play a html video with time jumps.
Scenario is like this:-
I have an array that contains time markers like this const obj = [{start: 2.64, end: 5.79}, {start: 7.95, end: 8.69}].
The requirement is that the video should start from 2.64 and play till 5.79 and then jump to 7.95 and then end at 8.69 and so on.
My solution is like this:-
const timers = this.state.timers;
let video = this.videoRef;
if (video) {
let index = 0;
video.addEventListener("timeupdate", () => {
if (parseInt(video.currentTime) == parseInt(timers[timers.length - 1].end)) {
video.pause()
}
if (timers[index]) {
if (parseInt(video.currentTime) == parseInt(timers[index].end)) {
if (index <= timers.length - 1) {
index++;
if (timers[index]) {
video.currentTime = timers[index].start;
}
}
}
}
this.setState({
tickTime: Math.ceil(video.currentTime)
})
})
video.play().then(res => {
video.currentTime = timers[0].start
})
}
It is working fine but when the video currenttime is like 2.125455 and in time object has end time 2.95, the parseInt function make both the time 3 and the video jumps to 3, so the 8 ms never plays, these 8ms are also very critical in my case
any solution on this please?
I am stuck for a while now
Well, I was able to resolve the problem
Thanks anyways
Here is the solution if anyone else facing it
const timers = this.state.timers;
let video = this.videoRef;
if (video) {
let index = 0;
video.addEventListener("timeupdate", () => {
if (video.currentTime >= timers[timers.length - 1].end) {
video.pause()
}
if (timers[index]) {
if ((video.currentTime) >= (timers[index].end)) {
if (index <= timers.length - 1) {
index++;
if (timers[index] && video.currentTime < timers[index].start) {
video.currentTime = timers[index].start;
}
}
}
}
this.setState({
tickTime: Math.ceil(video.currentTime)
})
})
video.play().then(res => {
video.currentTime = timers[0].start
})
}

get event from main calendar by expo calendar

I'm trying to use Calendar.getEventsAsync("calendarId", startDate,endDate) to get all events in my calendar from date "startDate" to "endDate". here is part of my code:
export class CalendarScreen extends Component {
...
async getEvents(date){
this.setState({
selectedStartDate: date,
});
console.log("1")
const { status } = await Calendar.requestCalendarPermissionsAsync();
if (status === 'granted') {
try {
console.log("2")
let startDate = new Date(this.state.startDate); //from today
let endDate = this.state.endDate.setDate(startDate.getDate()+1) ;/// to tomorrow
console.log(new Date(startDate))
console.log(new Date(endDate))
const eventi= await Calendar.getEventsAsync('1',new Date(startDate),new Date(endDate));
console.log(eventi)
} catch (error) {
return
}
}
}
render() {
return (
...
<CalendarPicker
onDateChange={this.getEvents}
/>
...
but out put is as bellow:
1
2
2022-07-21T12:11:02.000Z
2022-07-22T12:11:02.514Z
nothing as events

React Native birthday picker - componentWillREceiveProps

I need to build a birthday picker for a react naive application. I found the following https://github.com/ericmorgan1/react-native-birthday-picker but it has the deprecated method componentWillREceiveProps
Im not that experienced yet, so i don't know how to change this to the new methods to make it work. Can anyone help?
//
// DatePicker with an optional year.
//
// code from https://github.com/ericmorgan1/react-native-birthdaypicker/blob/master/BirthdayPicker.js
import React from 'react';
import { StyleSheet, View, Picker, } from 'react-native';
export default class BirthdayPicker extends React.Component {
static defaultProps= {
selectedYear: (new Date()).getFullYear(), // Year to initialize the picker to (set to 0 to not have a year)
selectedMonth: (new Date()).getMonth(), // Month to initialize the picker to
selectedDay: (new Date()).getDate(), // Day to initailize the picker to
yearsBack: 100, // How many years backwards (from starting year) you want to show
onYearValueChange: function(year, idx) { }, // Function called when year changes
onMonthValueChange: function(month, idx) { }, // Function called when month changes
onDayValueChange: function(day, idx) { }, // Function called when day changes
}
constructor(props) {
super(props);
this.startingYear = this.props.selectedYear;
this.state = {
year: this.props.selectedYear,
month: this.props.selectedMonth,
day: this.props.selectedDay,
}
}
componentWillReceiveProps(nextProps) {
this.setState({
year: nextProps.selectedYear, month: nextProps.selectedMonth, day: nextProps.selectedDay
});
}
// Tries to get the browser locale...
getLocale() {
if (navigator.language) { return navigator.language; }
if (navigator.languages && navigator.languages.length > 0) { return navigator.languages[0]; }
return "en-us"; // Default to English
}
// Loops through the months and gets the long name string...
getMonthNames() {
var locale = this.getLocale();
var monthNames = [];
for (var i = 0; i < 12; i++) {
var date = new Date(2000, i, 15);
monthNames.push(date.toLocaleString(locale, { month: "long" }));
}
return monthNames;
}
// Returns the number of days in the given month...
getNumDaysInMonth(year, month) {
// February is the only month that can change, so if there's no year, assume it has the maximum (29) days...
return (year == 0 && month == 1) ? 29 : (new Date(year, month + 1, 0).getDate());
}
// Returns the <Picker.Item> values for the years...
renderYearPickerItems() {
// If year was 0, change it to current...
var currentYear = (new Date()).getFullYear();
var centerYear = this.startingYear;
if (centerYear === 0) { centerYear = currentYear; }
// Set starting and ending years...
var startYear = centerYear - this.props.yearsBack;
var endYear = currentYear;
var years = [];
for (var i = startYear; i <= endYear; i++) {
years.push(<Picker.Item label={i.toString()} value={i} key={i} />);
}
years.push(<Picker.Item label="----" value={0} key={0} />);
return years;
}
// Returns the <Picker.Item> values for the months...
renderMonthPickerItems() {
var months = this.getMonthNames();
return months.map(function(month, index) {
return <Picker.Item label={month} value={index} key={index} />;
});
}
// Returns the <Picker.Item> values for the days (based on current month/year)...
renderDayPickerItems() {
// February is the only day that can change, so if there's no year, assume it has the maximum (29) days...
var numDays = this.getNumDaysInMonth(this.state.year, this.state.month);
var days = [];
for (var i = 1; i <= numDays; i++) {
days.push(<Picker.Item label={i.toString()} value={i} key={i} />);
}
return days;
}
// Occurs when year value changes...
onYearChange = (value, index) => {
// Check if days are valid...
var maxDays = this.getNumDaysInMonth(value, this.state.month);
var day = (this.state.day > maxDays) ? maxDays : this.state.day;
this.setState({ year: value, day: day });
this.props.onYearValueChange(value, index);
}
// Occurs when month value changes...
onMonthChange = (value, index) => {
// Check if days are valid...
var maxDays = this.getNumDaysInMonth(this.state.year, value);
var day = (this.state.day > maxDays) ? maxDays : this.state.day;
this.setState({ month: value, day: day });
this.props.onMonthValueChange(value, index);
}
// Occurs when day value changes...
onDayChange = (value, index) => {
this.setState({ day: value });
this.props.onDayValueChange(value, index);
}
render() {
return (
<View style={styles.container}>
<Picker style={styles.monthPicker} selectedValue={this.state.month} onValueChange={this.onMonthChange}>
{this.renderMonthPickerItems()}
</Picker>
<Picker style={styles.dayPicker} selectedValue={this.state.day} onValueChange={this.onDayChange}>
{this.renderDayPickerItems()}
</Picker>
<Picker style={styles.yearPicker} selectedValue={this.state.year} onValueChange={this.onYearChange}>
{this.renderYearPickerItems()}
</Picker>
</View>
);
}
}
const styles = StyleSheet.create({
container: { flexDirection: "row", },
monthPicker: { flex: 3, },
dayPicker: { flex: 1, },
yearPicker: { flex: 2, },
});

Expo-pixi Save stage children on App higher state and retrieve

I'm trying another solution to my problem:
The thing is: im rendering a Sketch component with a background image and sketching over it
onReady = async () => {
const { layoutWidth, layoutHeight, points } = this.state;
this.sketch.graphics = new PIXI.Graphics();
const linesStored = this.props.screenProps.getSketchLines();
if (this.sketch.stage) {
if (layoutWidth && layoutHeight) {
const background = await PIXI.Sprite.fromExpoAsync(this.props.image);
background.width = layoutWidth * scaleR;
background.height = layoutHeight * scaleR;
this.sketch.stage.addChild(background);
this.sketch.renderer._update();
}
if (linesStored) {
for(let i = 0; i < linesStored.length; i++) {
this.sketch.stage.addChild(linesStored[i])
this.sketch.renderer._update();
}
}
}
};
this lineStored variable is returning a data i've saved onChange:
onChangeAsync = async (param) => {
const { uri } = await this.sketch.takeSnapshotAsync();
this.setState({
image: { uri },
showSketch: false,
});
if (this.sketch.stage.children.length > 0) {
this.props.screenProps.storeSketchOnState(this.sketch.stage.children);
}
this.props.callBackOnChange({
image: uri,
changeAction: this.state.onChangeAction,
startSketch: this.startSketch,
undoSketch: this.undoSketch,
});
};
storeSketchOnState saves this.sketch.stage.children; so when i change screen and back to the screen my Sketch component in being rendered, i can retrieve the sketch.stage.children from App.js state and apply to Sketch component to persist the sketching i was doing before
i'm trying to apply the retrieved data like this
if (linesStored) {
for(let i = 0; i < linesStored.length; i++) {
this.sketch.stage.addChild(linesStored[i])
this.sketch.renderer._update();
}
}
```
but it is not working =(

React-Native — How to select a start and end date using react-native-calendars (WIX)?

I am trying to enable date range using react-native-calendars. On my app, the calendar loads a few 'markedDates'; now I need to implement a start and end date functionality without affecting these initial dates. Unfortunately, I am struggling to achieve that. Any ideas on how can I do that?
Thank you in advance.
Pseudo-code
Load calendar with marked dates
Tap on start date
Tap on end date
Continue
Component
export default class Dates extends Component {
static navigationOptions = {
title: 'Choose dates',
}
constructor(props) {
super(props)
this.state = {
selected: undefined,
marked: undefined,
}
}
componentDidMount() {
this._markDate()
}
_markDate = () => {
nextDay = []
const marked = {
[nextDay]: { selected: true, marked: true },
}
Util._findShows(resp => {
resp.map(data => {
nextDay.push(data.date)
})
var obj = nextDay.reduce((c, v) => Object.assign(c, { [v]: { marked: true, dotColor: 'black' } }), {})
this.setState({ marked: obj })
})
}
_selectDate = obj => {
this.setState({ selected: obj.dateString })
}
render() {
return (
<View style={styles.container}>
<CalendarList
// Callback which gets executed when visible months change in scroll view. Default = undefined
onVisibleMonthsChange={months => {
console.log('now these months are visible', months)
}}
// Max amount of months allowed to scroll to the past. Default = 50
pastScrollRange={0}
// Max amount of months allowed to scroll to the future. Default = 50
futureScrollRange={12}
// Enable or disable scrolling of calendar list
scrollEnabled={true}
// Enable or disable vertical scroll indicator. Default = false
showScrollIndicator={true}
markedDates={
// [this.state.selected]: { selected: true, disableTouchEvent: true, selectedDotColor: 'orange' },
this.state.marked
}
onDayPress={day => {
this._selectDate(day)
}}
/>
<View style={styles.ctaArea}>
<TouchableOpacity style={styles.button} onPress={() => this.props.navigation.navigate('Dates')}>
<Text style={styles.btTitle}>Continue</Text>
</TouchableOpacity>
</View>
</View>
)
}
}
I had the same struggle but so I decided to make my own version.
I'm sure it can be done better and have more functionalities but it works okay for me
const [dates, setDates] = useState({});
// get array of all the dates between start and end dates
var getDaysArray = function(start, end) {
for (var arr=[], dt = new Date(start); dt <= new Date(end); dt.setDate(dt.getDate() + 1)){
arr.push(useFormatDate(new Date(dt)));
}
return arr;
};
// empty object
const emptyObj = (obj: Object) => {
var props = Object.getOwnPropertyNames(obj);
for (var i = 0; i < props.length; i++) {
delete dates[props[i]];
}
}
// check if first date is smaller or equals to second date
const compareDate = function(first: string, second: string) {
return (new Date(first) <= new Date(second) ? true : false);
}
// fill with color the date between first and second date selected
const fillRangeDate = function(first: string, second: string) {
emptyObj(dates);
let newDates = dates;
newDates[first]={selected: true, Colors[colorScheme].tint};
newDates[second]={selected: true, color: Colors[colorScheme].tint};
var range = getDaysArray(first, second);
for (var i = 1; i < range.length - 1; i++)
newDates[range[i]]={color: '#70d7c7', textColor: 'white'};
setDates({...newDates})
}
const selectDate = (day) => {
let selectedDate = day.dateString;
let newDates = dates;
// if 2 dates are selected
if (Object.keys(dates).length >= 2) {
var props = Object.getOwnPropertyNames(dates);
if (compareDate(props[0], selectedDate)) {
fillRangeDate(props[0], selectedDate);
} else {
emptyObj(dates);
}
} else {
// 1 date selected
if (Object.keys(dates).length == 0) {
newDates[selectedDate]={selected: true, color: Colors[colorScheme].tint};
} else if (Object.keys(dates).length == 1) { // 2 dates selected
newDates[selectedDate]={selected: true, color: Colors[colorScheme].tint};
// if 2nd date < 1st date, cancel range
var props = Object.getOwnPropertyNames(dates);
if (compareDate(props[0], props[1])) {
var range = getDaysArray(props[0], props[1]);
for (var i = 1; i < range.length - 1; i++) {
newDates[range[i]]={color: '#70d7c7', textColor: 'white'};
}
} else {
emptyObj(dates);
}
}
}
setDates({...newDates})
}
You'll also need to add this function that I implemented as a hook:
const useFormatDate = (date: Date) => {
function padTo2Digits(num) {
return num.toString().padStart(2, '0');
}
return [
date.getFullYear(),
padTo2Digits(date.getMonth() + 1),
padTo2Digits(date.getDate()),
].join('-');
};
Help me to improve this code and maybe create a merge request on the wix/react-native-calendar
Hope this helps