how to add minutes to Date() in react-native? - react-native

I want to add 5 minutes to current time and store it to this.state.date.
However,
this.setState({
date: new Date() + new Date(0,0,0,0,0,5,0),
});
gives me some strange error, saying
`props.date.getTime is not a function. (In 'props.date.getTime()', 'props.date.getTime' is undefined)
DatePickerIOS_render
DatePickerIOS.ios.js:125
EDITED: According to this post I also tried below,
this.setState({
date: this.state.date.setMinutes((new Date()).getMinutes()+5)
});
but it still gives me the same error message. What is the correct way to add minutes to Date() in react-native?
Btw, I'm using datepickerios on another part of the app, and not sure why the error is related to DatePickerIOS.ios.js in the first place. The other part of the app which actually uses the DatePickerIOS works fine without error.
EDITED AGAIN:
Below is the full function. This function is called from a SegmentedControlIOS which has values ['5min from now', '15min from now', '30min from now', 'custom'].
_onTimeChange = (event) => {
switch (event.nativeEvent.selectedSegmentIndex) {
case 0:
// 5min
return this.setState({
date: this.state.date.setMinutes((new Date()).getMinutes()+5),
time: this.state.date.toLocaleTimeString()
});
case 1:
// 15min
return this.setState({
date: this.state.date.setMinutes((new Date()).getMinutes()+15),
time: this.state.date.toLocaleTimeString()
});
case 2:
// 30min
return this.setState({
date: this.state.date.setMinutes((new Date()).getMinutes()+30),
time: this.state.date.toLocaleTimeString()
});
case 3:
// show modal with datepicker (this one works fine)
return this.setModalVisible(true);
}
}
What happens: If I change selection from the segmented control once, a yellow warning bar with props error message is shown at the bottom of my simulator. If I change selection once again, then the red screen shows up with '_this5.state.date.setMinutes is not a function'.
So it looks like
date: this.state.date.setMinutes((new Date()).getMinutes()+5)
does add minutes, but when I do it twice it ends up in error.
Please help!

Try this:
var d = new Date(); // get current date
d.setHours(d.getHours(),d.getMinutes()+5,0,0);
EDIT
var d = new Date(); // get current date
d.setHours(d.getHours(),d.getMinutes()+5,0,0);
this.setState(date:d,time:d.toLocaleTimeString());

Related

How to set date in react native push notification?

I am using react native push notification.
But when i am trying to push local schedule, notification not show as time expected. It always showed when i reload the app (same behaviour like PushNotification.localNotification
how to set date for parameter inside PushNotification.localNotificationSchedule ? i am confuse to set value there. I already using timestamp but looks like the value is different.
1578909865373 => using date.now
1578907260 => i convert from string date to timestamp
my code :
function toTimestamp(strDate){
var datum = Date.parse(strDate);
return datum/1000;
}
const dated= toTimestamp('01/13/2020 16:21:00');
PushNotification.localNotificationSchedule({
//... You can use all the options from localNotifications
message: "testing notification", // (required)
date: date: new Date(dated) // in 60 secs
// date: new Date("2020/01/13")
});
}
please help how to insert or convert right value for date.
Thank you
Turn out i dont have to divide by 1000
timestamp is milliseconds.
so right function is
function toTimestamp(strDate){
var datum = Date.parse(strDate);
return datum;
}

vuejs datepicker selected event is no working properly

I'am vuejs-datepicker . I'm trying to print the selected date which is stored in a variable in data. Initially the value of the variable is empty. vuejs-datepicker supports the selected event. so when the event is triggering, I mean if date is selected the selected event get triggered. but does not print ta current selected date rather it print empty string. if I again select another date the it prints the previous date. It is printing the the previous stored date. code is given below
Uses
<date-picker :bootstrap-styling="true" class="datepicker form-control"
placeholder="Select Date" v-model="appointment.appointmet_date"
#selected="dateSelected()"></date-picker>
dateSelected method
dateSelected () {
console.log(this.appointment.appointmet_date)
},
data property
data () {
return {
appointment: {
appointmet_date: '',
}
}
}
When I entered first date it printed null. when I entered date second time it printed the time entered first time
upadate
dateSelected () {
// console.log(this.appointment.appointmet_date)
var self = this
this.$nextTick(() => console.log(self.appointment.appointmet_date))
this.$http.post(apiDomain + 'api/getAvailableDate', {avlDate: self.appointment.appointmet_date})
.then(response => {
console.log(response)
})
}
when i entered first date it printed null. when i entered date second time it printed the time entered first time
Yes because the selected event is fired before the Vue nextTick function which updates the v-model.
Please below code and working codesandbox demo.
dateSelected (e) {
console.log(this.appointment.appointmet_date);
this.$nextTick(() => console.log(this.appointment.appointmet_date))
},
For future visitors - simply make the post request within the Vue nextTick() like so:
dateSelected () {
...
this.$nextTick(() => {/* post call here */})
}

How to wait for full name to enter in a text box in protractor

I am entering a text in a text box using send keys but it is not waiting for text to get entered completely and clicking next button so text is not written completely. How to resolve this issue?
I an entering random name by using date function and appending a constant before this as shown. Now when it enters through sendkeys, first time it gets entered fully like a45 but second time it is entering like a and clicking next button hence test case is getting failed.
How to wait protractor to let the text written completely?
var text = 'a' + date.getHours(); + date.getMinutes();
element.sendKeys(text);
element.click();
Expected results: a345
Actual: a
Can someone help me in this case and tell me how to make protractor wait for text to be written completely and then click next button?
Writing this as async / await. Setting a browser.sleep will just add time to your test without knowing if the value is correct. You could use a browser.wait instead which will poll for a condition to be true or to timeout (in this case, 5 seconds). The condition we are going to satisfy is if the value attribute is equal to the text.
Note: I changed element since that refers to a global object to someButton and someTextBox.
const text = 'a' + date.getHours(); + date.getMinutes();
// send the text
await someTextBox.sendKeys(text);
// poll for a condition to be true or to timeout of 5 seconds
await browser.wait(async () => {
// keep checking until the value attribute reflects the entered keys
return (await someTextBox.getAttribute('value')) === text ;
}, 5000);
await someButton.click();
var date = new Date();
var msg ='a' + date.getHours() + date.getMinutes();
await element.sendKeys(await msg);
await elemnet.click();
Try using async/await. For ref https://github.com/angular/protractor/blob/master/docs/async-await.md
Hope above inputs help you.
remove ;from date.getHours(); in your code to get what your are expecting.
try this out
var date = new Date();
var hour = date.getHours();
var min = date.getMinutes();
var text = 'a' + hour + min;
and then wait for element to get inserted
browser.driver.sleep(500);
element.sendKeys(text);
element.click();
You need to add an await to your actions so that you wait for the promise to complete.
You could also add a check at the end of a custom send keys method that waits for the send keys to be complete.
await elem.clear();
await elem.sendKeys(keys);
return (await elem.getAttribute('value')) === keys;
You have some good answers here already but if they do not work one thing that helped me on a previous project was to split the string and enter character by character.
text.split('').forEach(char => {
element.sendKey(char);
});

Agenda - dynamically change selected day

I'm having trouble to dynamically change the selected day. For example, I want to change selected day to today when leaving the screen; I don't want to have other selected day than today when leaving... How can I do that? I'm using the agenda.
Also, I want to change the selected day when the user clicks on some button in that screen. My agenda list date is not changed at all if I just set the state for selectedDay...
My code for now;
componentDidMount() {
this.props.navigation.addListener('didBlur', (playload)=>{
console.log(playload);
this.onDayPress(Moment().format('YYYY-MM-DD').toString());
});
}
My agenda:
<Agenda
// the list of items that have to be displayed in agenda. If you want to render item as empty date
// the value of date key kas to be an empty array []. If there exists no value for date key it is
// considered that the date in question is not yet loaded
items={this.state.items2}
// callback that gets called when items for a certain month should be loaded (month became visible)
//loadItemsForMonth={}
// callback that fires when the calendar is opened or closed
onCalendarToggled={(calendarOpened) => {}}
// callback that gets called on day press
onDayPress={this.onDayPress.bind(this)}
// callback that gets called when day changes while scrolling agenda list
onDayChange={(day)=>{
this.setState({day: day})
console.log('OnDayChange: ' + day);
}}
// initially selected day
//selected={ Moment().format('YYYY-MM-DD').toString()}
//selected={'2018-02-20'}
selected={this.state.selectedDay}
// Minimum date that can be selected, dates before minDate will be grayed out. Default = undefined
minDate={this.state.minDate}
// Maximum date that can be selected, dates after maxDate will be grayed out. Default = undefined
maxDate={this.state.maxDate}
...
onDayPress method;
onDayPress(day) {
//console.log('Predn zamenjam selected day: ' + this.state.selectedDay);
if(day.dateString === undefined) {
if(day !== undefined) {
//console.log('day: ' + day);
this.setState({
selectedDay: day
});
return true;
}
}
this.setState({
selectedDay: day.dateString
});
this.getNextThreeDays(day.dateString);
this.getQuotes(day.dateString);
}
Environment
npm ls react-native-calendars: 1.19.4
npm ls react-native: ^0.55.4
Few years late but managed to solve this using refs
import React, { createRef } from 'react';
const agendaRef = createRef();
When rendering the agenda include the reference
<Agenda
ref={agendaRef}
...
/>
For the onPress function for the button include the call to chooseDay
const date = '2020-10-01' // the date you want to go to
agendaRef.current.chooseDay(date)
It should animate as if the date button was tapped

React Native - Saving search terms after delay

I am creating a search toolbar that allows the user to see their most recent searches, using Realm Browser as my database. I save a search whenever the user types in the TextInput component, however, I don't want to add a search term after each key stroke, but only after the user has stopped typing for certain amount of time.
handleOnChange function will update state and only call getResults after 2 seconds
handleOnChange(text) {
this.setState({
searchStr: text
}, () => setTimeout(() => {
this.getResults()
}, 2000))
}
In getResults, I call my addRecentSearch function if certain criteria is met.
getResults() {
let searchTags = []
let searchCalcs = []
let tagNames = this.state.tags.map((tag) => {
return tag.name
})
if (this.state.searchStr.length >= 2 || this.state.tags.length !== 0) {
searchCalcs = Realm.searchCalcs(this.state.searchStr, tagNames)
Realm.addRecentSearch(this.state.searchStr)
}
this.setState({
results: searchCalcs,
tagsForFiltering: searchTags
})
}
So I use setTimeout to allow enough time for my state to get updated when the user types. Then, once the states been updated, I will want to add the search query. However, I'm not getting the results I expected when grabbing the most recent searches.
For example:
Type: "h"
Result: nothing happens as str must be at least 2 characters in length
Type: "he"
Result: meets criteria, and will add "he" as a recent search term.
Arr: ["he"]
Type: "heart" (Note: adding 3 characters in succession)
Result: It seems that even with the timeout function, my getResults function is being called (thus adding the search query for each character I added)
Arr: ["he", "heart", "heart", "heart"]
I want my arr to look like:
arr: ["he", "heart"]
You aren't fully debouncing in your example. You are only delaying everything by 2000ms. You need to create a timer and then reset it every time a change happens (by clearing and starting timer again). In this way, only the final 'delay' takes effect. Make sense?
You are very close to have written your own debounce function, so you can use clearTimeout, or there are some libraries that do it. See Lodash https://lodash.com/docs/#debounce