Moment.js datepicker won't accept my dates - reactjs

I'm currently working on a project using React.js.
I’m using material-ui datepicker and I'm blocking all dates except the 14 upcoming dates. What I want is that every Thursday I get 14 new dates in my datepicker.
I'm supposed to add my beginningOfWeek and endOfWeek into my maxDate and minDate, but it's currently not working and I can't figure out how to get it right.
It types out the correct answer in the log but when I press the datepicker I'm getting an error and the debugger says:
TypeError: d2.getFullYear is not a function at monthDiff
What am I doing wrong?
I've used this example for my own code. How to get the date ranges of a given week number in JS
This is my code:
var moment = require('moment');
const w = moment().weekday();
const daysToSubtract = (w + 3)%7;
const beginningOfWeek = moment(new Date()));
const endOfWeek = moment(new Date()).add(-daysToSubtract, 'days');
console.log(beginningOfWeek.format('MM/DD/YYYY h:mm a'),
endOfWeek.format('MM/DD/YYYY h:mm a'))
<div className="center-container">
<DatePicker hintText={newdate} mode="landscape" maxDate={endOfWeek}
minDate={beginningOfWeek}/>
</div>

I solved it by doing this. I changed my maxDate into maxDate = {new Date(endOfWeek)}/>
const moment = require('moment');
const w = moment().weekday();
const daysToSubtract = ((w + 3 + Math.floor(hours/16)))%7 ;
const beginningOfWeek = moment().add(-daysToSubtract, 'days');
const endOfWeek = moment().add(14-daysToSubtract, 'days');
console.log(beginningOfWeek);
console.log(endOfWeek);
<div className="center-container">
<DatePicker hintText={newdate} mode="landscape" minDate={new
Date()} maxDate = {new Date(endOfWeek)}/>
</div>

Related

How to change the time format from HH:MM to 2023-01-25T19:15:27.615Z in React Js

Basically, the most scenarios of programming in react js. The conversion of time is from this 2023-01-25T19:15:27.615Z to HH:MM. So, here in my scenario I want to make the vice versa of it.
within moment you can do this by telling moment the format you are providing for instance moment('13:00', 'HH:mm'); is valid and the return object can be converted to ISO string with .toISOString()
You can use date-fns library.
Firstly install npm install date-fns
import {format} from 'date-fns'
...
format(new Date(),'HH:mm') // MM for months you have to use mm
An external library is not needed to set the hours and minutes for the current date and get an ISO string — a simple function will work:
function timeToIsoString (
hoursMinutes,
{ date = new Date(), utc = false } = {},
) {
const [h, m] = hoursMinutes.split(":").map(Number);
const d = new Date(date.getTime());
d[utc ? "setUTCHours" : "setHours"](h);
d[utc ? "setUTCMinutes" : "setMinutes"](m);
return d.toISOString();
}
const input = "12:34";
// Interpreting time in local time zone:
const output1 = timeToIsoString(input);
console.log(output1);
// Interpreting time in UTC:
const output2 = timeToIsoString(input, { utc: true });
console.log(output2);
// Starting with an existing date:
const date = new Date(Date.UTC(2008, 8, 15));
const output3 = timeToIsoString(input, { date, utc: true });
console.log(output3); // "2008-09-15T12:34:00.000Z"

Convert month and year into normal date format in reactjs

<DatePicker onChange={this.dateSelect} value={this.state.dateselected} format={"MM/YYYY"} mode="month" picker="month" disabledDate={(current) => {
return moment().add(-4, 'month') >= current;
}} />
date picker didn't shows the value on edit.. We get date as MM/YYYY format from backend. How to display?
You can convert the date using moment when passing the value prop, as:
<DatePicker
value={moment(this.state.dateselected, "YYYY/MM")}
onChange={onChange}
format={"YYYY/MM"}
picker="month"
disabledDate={(current) => {
return moment().add(-4, "month") >= current;
}}
/>
View demo on codesandbox
You need to parse the date components and pass them into the Date() constructor.
const [month, year] = "01/2022".split("/");
const date = new Date(parseInt(year), parseInt(month) - 1);
console.log(date.toString());
// 'Sat Jan 01 2022 00:00:00 GMT-0600 (Central Standard Time)'
you can convert it via dateformat library for example:
1. npm install dateformat
2. import dateFormat from 'dateformat';
3. dateFormat("2022-03-7T08:59:00.000Z", "mmmm dS, yyyy") to get March 7th, 2022
or dateFormat("2022-03-7T08:59:00.000Z", "dddd, mmmm dS, yyyy") to get Tuesday, March 7th, 2022.
https://www.npmjs.com/package/dateformat
I think it gives an error is because new Date() function only accepts a specific format YYYY-MM-DD or YYYY/MM/DD so if your Date is not in that format then it will give you an error.
So what you can do is convert your date into a string and pass date, month, year as arguments. You can use the below code for that.
function convertFromStringToDate(responseDate) {
let dateComponents = responseDate.split('T');
let datePieces = dateComponents[0].split("-");
let timePieces = dateComponents[1].split(":");
return(new Date(datePieces[2], (datePieces[1] - 1), datePieces[0],
timePieces[0], timePieces[1], timePieces[2]))
}
convertFromStringToDate("21-03-2020T11:20:30")

Why I am getting this warning message, does not conform to the required format, "yyyy-MM-dd" in ReactJS?

I tried to assign a value to the Date (input). But I got the warning message and the Date field was also not getting updated with the assigned value.
Warning message: The specified value "Sun May 23 2021 16:06:23 GMT+0530 (India Standard Time)" does not conform to the required format, "yyyy-MM-dd".
How to assign a value (date) to the Date Input field in React using useState() hook?
Please let me know your suggestions. Thanks.
useState:
const todayDate = new Date();
const [ expenseDate, setExpenseDate ] = useState(todayDate);
JSX Part:
<label htmlFor="date-val">
<input type="date" name="date-val" value={expenseDate} onChange={onDateChangeHandler} required />
</label>
You need to convert your Date in specific yyyy-mm-dd format
Try this
const todayDate = new Date();
const formatDate = todayDate.getDate() < 10 ? `0${todayDate.getDate()}`:todayDate.getDate();
const formatMonth = todayDate.getMonth() < 10 ? `0${todayDate.getMonth()}`: todayDate.getMonth();
const formattedDate = [todayDate.getFullYear(), formatMonth, formatDate].join('-');
const [expenseDate, setExpenseDate] = useState(formattedDate);
The resulting value includes the year, month, and day, but not the
time
For better understanding, go through official documentation

How to restrict date selection in React native ios/android datepicker

I would like to restrict users from selecting particular dates based on business logic in react native ios/ android date pickers. Currently in the document i only see that a min date and max date can be provided.
So is there a way to only restrict lets say (5 , 6, 10, 12 , 18) of a month?
Note: these dates are just an example would change from a case to case scenario
For IOS example
<DatePickerIOS
date={this.state.chosenDate}
onDateChange={(date) => {
if(isAllowedDate(date)) {
this.setState({chosenDate: newDate})
}
else {
this.setState({error:'you can not select this date ...'})
}
}}
/>
use react-native-datepicker module for iOS and Android , set a method to check if date valid or not
render(){
return(
...
<DatePicker
mode="date"
placeholder="select date"
format="YYYY-MM-DD"
onDateChange={this.saveDateIfValid}
/>
...
)
}
saveDateIfValid = (date) =>
{
if(date){
let dateArray = data.split("-");
let validDays = [5,6,10,12,18];
let selectedDay = parseInt(dataArray[2]);
if(validDays.indexOf(selectedDay) > -1){
//date is valid
this.setState({date : date});
return; //end the method
}
}
//not valid
this.setState({date : null});
}

Angular strap binding datePicker not working with start and end date?

I use angular strap datePicker
<input type="text" name="dateFrom" ng-model="dateFrom" bs-datepicker
data-end-date="{{endDate}}" data-start-date="{{startDate}}" />
How ever when change endDate or startDate from code it does update in the DOM but the date picker remains unaware of this change, is there some kind of update I need to trigger?
The change is done via a ng-click with function on the same scope, that then sets a new value for endDate and startDate.
Like so (CoffeeScript):
$scope.setDateRange = (dateRange) ->
if dateRange is "past"
$scope.endDate = "-1d"
$scope.startDate = ""
if dateRange is "now"
$scope.endDate = ""
$scope.startDate = ""
if dateRange is "future"
$scope.endDate = ""
$scope.startDate = "+1d"
Edit:
Here is the solution:
On the controller constructor I store the date from and to controls:
dateFromCtrl = $element.find 'input[name="dateFrom"]'
dateToCtrl = $element.find 'input[name="dateTo"]'
Then when setDateRangeis called I made few helper methods to call the datepicker setEndDate and setStartDate methods:
setEndDate = (date) ->
dateFromCtrl.datepicker 'setEndDate', date
dateToCtrl.datepicker 'setEndDate', date
setStartDate = (date) ->
dateFromCtrl.datepicker 'setStartDate', date
dateToCtrl.datepicker 'setStartDate', date
setDateRange = (dateRange) ->
if dateRange is "past"
setEndDate "-1d"
setStartDate ""
if dateRange is "now"
setEndDate ""
setStartDate ""
if dateRange is "future"
setEndDate ""
setStartDate "+1d"
Try using the setStartDate() and setEndDate() calls:
http://bootstrap-datepicker.readthedocs.org/en/latest/methods.html#setstartdate
Or you might look at the datepicker that is now provided by the Angular folks, so it has especially nice integration within Angular: http://angular-ui.github.io/bootstrap/

Resources