Selecting date gives an object, not the dates - angularjs

When I select dates and apply the filter, the startDate and endDate both are objects and i can't seem to be able to get the selected days.
I have already tried to select the attributes inside of the object, but it doesn't give me a good date.
I have the following code:
CONTROLLER
$scope.datePicker = {
date: {startDate: null, endDate: null},
options: {
maxSpan: {
days: 31
},
maxDate: moment(),
locale: {
separator: ' - ',
format: "D/MM/YYYY"
},
monthNames: ['Janeiro', 'Fevereiro', 'Março', 'Abril', 'Maio', 'Junho', 'Julho', 'Agosto', 'Setembro',
'Outubro', 'Novembro', 'Dezembro'
]
}
};
HTML
<input class="filter-select date-picker" type="text"
date-range-picker
options="datePicker.options"
max="datePicker.options.maxDate"
ranges="datePicker.opstions.maxSpan.days"
ng-model="datePicker.date" />
I also have a watcher that logged the following image:
Does anyone knows how to get the the startDate and endDate values as a simple string or a Date format?

You can use moment to get the date with the format you expect.
For Example:
let startDate = moment($scope.datePicker.date.startDate).format("DD-MM-YYYY");
let endDate = moment($scope.datePicker.date.startDate).format("DD-MM-YYYY");
To know about various date formats you can check this on moment date formats

Related

Store date as "yyyy-MM-dd" in Mongoose via Material UI DatePicker

As I'm not exactly used to work with dates on Javascript, it's been quite hard to tackle it without asking for help, and I've been struggling for hours on this.
My goal is to choose a date using Material UI DatePicker and store it as a string following the "yyyy-MM-dd" format.
In my last attempt, I tried this:
const [userData, setUserData] = useState({
rating: 0,
review: "",
date: Date(),
});
Then, in DatePicker:
<LocalizationProvider dateAdapter={DateAdapter}>
<DesktopDatePicker
label="Watched on"
inputFormat="MMM dd, yyyy"
disableMaskedInput={true}
name="date"
value={userData.date}
onChange={(date) => {
setUserData((prevValue) => {
const dateWatched = startOfDay(date);
return {
...prevValue,
date: dateWatched.toISOString().slice(0, 10),
};
});
}}
renderInput={(params) => <TextField {...params} />}
/>
</LocalizationProvider>;
If I console.log(dateWatched.toISOString().slice(0, 10), when I pick a date it logs correctly. However, the date displayed on DatePicker mismatches. So, let's say I choose December 14, 2021. It logs 2021-12-14 like I wanted, but the DatePicker will show December 13, 2021. For the record, my local time is GMT -03:00, and I think this may be the culprit. I want to take time zones out of the way, so no matter where you are and the time of the day, you'll always get the correct date string saved on Mongoose and displayed correctly on DatePicker.
note: I'm using date-fns library.

React Data Table Component and Moment

I am using React Data Table Component for displaying table data - which works great!
I have a row field for lastLogin time, which is stored in MongoDB as a model like so:
lastLogin: [{
type: Date,
required: false,
}],
My data table component looks like so:
<DataTable
noHeader
pagination
paginationPerPage={15}
paginationRowsPerPageOptions={paginationRowsPerPageOptions}
responsive
columns={columns}
sortIcon={<ChevronDown />}
className="react-dataTable"
data={store.data}
/>
Using columns when I try and render the date without moment, it works fine:
{
name: 'Last Login',
selector: (row) => row.lastLogin,
},
will result in:
row 1: 2021-11-17T01:16:55.093Z
row 2: (empty)
However, when formatting with moment, it seems to be obtaining the previous records results.
{
name: 'Last Login',
selector: (row) => row.lastLogin,
format: (row) => moment(row.lastLogin).format('lll'),
},
will result in:
row 1: Jan 1, 2021 12:00 AM
row 2: Nov 17, 2021 1:15 PM
This code is work correct, and the result its expected base on how the moment work.
moment work with current time as a default time to do a process, so that, if you pass a date value, then you will work and format this value, else will work and format current date.
for example:
var now = moment(undefined).format('lll');
console.log(now)
this will be equl for:
var now2 = moment().format('lll');
console.log(now2)
Demo Link
Ok... this one has been resolved... silly syntax error.
The login date on the model was setup as an array:
lastLogin: [{
type: Date,
required: false,
}],
Should be:
lastLogin: {
type: Date,
required: false,
},

How to pass only the date to the database (without passing the time) using react-datetime picker

How to pass only the date to the database (without passing the time) using react-datetime picker.
Currently in my code it will pass both date and time to the backend like this (2021-09-07T18:30:00.000Z).
I want to pass only the date like (2021-09-07) without the time.
using react-datetime picker
please help me!
<ReactDatetime
inputProps={{
placeholder: "MM/DD/YY",
}}
dateFormat="DD/MM/YYYY"
timeFormat={false}
onChange={(value) =>
formik.handleChange({
target: {
name: "date_of_the_event",
value,
},
})
}
onBlur={formik.handleBlur}
value={formik.values.date_of_the_event}
/>
you can get your date as a string with that format by using the below statement
const formattedDate = date.toLocaleString('en-GB', { day: 'numeric', month: 'numeric', year: 'numeric' })
If you need to swap date and month use 'en-US'
If you want any custom format get one by one and append it like below
const formattedDate =
`${date.getFullYear()}-${date.getMonth()}-${date.getDate()}`
In the handleChange method, you can format the date like this.
const formattedDate = `${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()}`
If you use a library like momentjs, you can simply format the date like this
const formattedDate = moment(date).format('YYYY/MM/DD');

Date range validation - Start Date must not be same as End Date in jquense / yup

I'm using Yup for my form validations in reactjs. My form has two dates, startDate and endDate. I have successfully implemented range validation. but in my scenario startDate must be grater than endDate (should not be equal). but schema below only checks for less than scenario for endDate. where as it accept same dates. Please help.
schema I'm using is:
schema = Yup.object().shape({
startDate: Yup.date().min(new Date(), 'Please choose future date').typeError('Start Date is Required'),
endDate: Yup.date().min(Yup.ref('startDate'), 'End date must be grater than start date').typeError('End Date is Required'),
});
I know it's too late but I'm posting this answer, I found this solutions if it can help :
schema = Yup.object().shape({
startDate: yup
.date()
.required("Start Date is Required"),
endDate: yup
.date()
.min(
yup.ref("startDate"),
"End date must be grater than start date"
)
.test({
name: "same",
exclusive: false,
params: {},
message: "End date must be grater than start date",
test: function(value) {
const startDate = moment(this.parent.startDate).format("YYYY-MM-DD")
const endDate = moment(value).format("YYYY-MM-DD")
return !moment(startDate).isSame(moment(endDate))
},
}),
});

Dynamically add filter in ng-repeat

I am building a table where the rows and columns are built entirely based on the data that is sent to it.
I'm very close to having it work, I'm having trouble figuring out how to build a custom filter and pass in the filter patterns dynamically
The object that makes up the columns looks like
{ name: 'transactionDate', displayName: 'Date / Time', displayOrder: 1, filter: "date: 'MM/dd/yy hh:mm a'" }
The object that makes up the transaction for the rows looks like this:
{ transactionDate: '2015-06-11', transactionType: 'This Type', transactionAmount: 25 }
The HTML I have is this:
<td ng-repeat="col in columns">{{transaction[col.name] | dynamicFilter: col.filter}}</td>
The filter I currently have built is:
function dynamicFilter($filter) {
return function (value, filter) {
console.log(filter);
console.log(value);
var test = $filter(filter)(value);
return test;
}
}
Both filter and value are getting passed correctly. I'm having trouble figuring out how to apply the filter to the value before returning. A value that might be passed in would 2015-06-10T16:17:14 be and a filter that would be passed in could be date: 'MM/dd/yy hh:mm a' to create date/time filter. Or 21 and currency for a dollar value.
I would like to be able to use Angular's built in features in a similar way you could on the view
For these dynamic filters that have partial params (such as the format you're providing with date), you have to remove the param from the filter and apply it later.
So filter: "date: 'MM/dd/yy hh:mm a'", needs to be just filter: "date".
The additional constraint, MM/dd/yy hh:mm a, would be sent along with the value $filter(filter)(value, 'MM/dd/yy hh:mm a');
To do this generically, you can take advantage of apply. The Object can be:
{filter: { type: "date", params: ['MM/dd/yy hh:mm a'] } }
And the directive can have (assuming you send the params as well):
var filterFn = $filter(filter.type);
return filterFn.apply(filterFn, [value].concat(filter.params));
EDIT: here's a JSFiddle with two buttons, the first demonstrates your original approach with "date: 'MM/dd/yy hh:mm a'", and the second demonstrates applied approach that I outline above http://jsfiddle.net/4whemakt/
You can apply and return the filtered value conditionally in your dynamicFilter. Something like this
function dynamicFilter($filter) {
return function (value, filter) {
if (filter.indexOf('date:') !== -1) {
//Note: I am using moment js to format the date
return moment(value).format(filter.match(/'([^']+)'/)[1]);
}
else {
return $filter(filter)(value)
}
}
}
moment.js reference http://momentjs.com/

Resources