I have the following in Ionic and I'd like to let the user choose a datetime value but with one condition: If hour is equal to '21' then minutes must be '00' (not '30'), otherwise minutes value can be equal to '00' or '30'. Ideas?
<ion-datetime
hourValues="9,10,11,12,13,14,15,16,17,18,19,20,21 #hour"
[minuteValues]="hour != 21 ? '00,30' : '00'"
[(ngModel)]="time"
name="time"
required>
</ion-datetime>
It was not possible because the "minuteValue" is set first when u click on ion-datepicker to select date & time.
one way to achieve this is to compare your selected hour in .ts file and assign particular value based on hour to the minute like below.
In .html file.
<ion-datetime
hourValues="9,10,11,12,13,14,15,16,17,18,19,20,21 #hour"
minuteValues="0,30"
[(ngModel)]="time"
name="time"
displayFormat="MM DD,YYYY HH:mm"
(ionChange)="timeValue()"
required>
</ion-datetime>
In .ts file:
timeValue()
{
let hour = this.time.split('T')[1].split(':')[0];
let minute = this.time.split('T')[1].split(':')[1];
if(Number(hour) === 21)
{
minute = '00';
}
let date = new Date(this.timey);
date.setHours(Number(hour));
date.setMinutes(Number(minute));
console.log("------------"+date);
}
Related
I'm currenlty working on yup validation for a page in project. I'm stuck on the following:
User chooses date, timezone and specific time of the event (he can choose times from 00:00 to 23:45 every fifteen minutes). Now, I need to validate if chosen time is in the future. I am really confused: should I first convert current moment to users chosen timezone, or convert user's moment to local timezone, or something else.
Here's what I did first when I was careless about the timezone:
[keys.startTime]: yup
.number()
.required(errors.required)
.when(['date'], (date, schema: any) => {
const currentTimeInMinutes = moment().hours() * 60 + moment().minutes()
if (
moment(date).date() === moment().date() &&
moment(date).month() === moment().month() &&
moment(date).year() === moment().year()
)
return schema.min(currentTimeInMinutes, errors.pastTime)
}),
But then I realised that I didn't take into account chosen timezone.
Start time here represents number of minutes from 00:00 to chosen time, for example if user chooses 00:15, startTime will be 15.
Thanks in advance.
You need to compare - the current time (at the point of submission) with the user's selected/entered date and startTime both in the user's selected zone.
// Calculate the offset of the timezone that user selected from UTC
const utcOffset = '+05:30'; // Example of a time zone in India
const currentTime = moment().utcOffset(utcOffset);
const userSelectionTime =
moment(date).utcOffset(utcOffset)
.startOf('day')
.add(startTime, 'minutes');
/*
* Check if the difference between the `userSelectionTime` and the `currentTime`
* is greater than 0 minutes (you can change this as per your requirements)
*/
const selectionIsValid = userSelectionTime.diff(currentTime, 'minutes') > 0;
I have a DayPickerInput element from react-day-picker plugin and I don't know how to disable all days after a month(31 days) starting with current day. Any help please?
Thanks.
The documentation could be a clearer. This should do it for you:
<DayPickerInput
value={moment(minDate).format('YYYY-MM-DD')}
dayPickerProps={{
disabledDays: {
after: new Date(2018, 3, 20),
},
}}
onDayChange={day => console.log(day)}
/>
Replace the new Date(y, m, d) with your date.
[Edit per my comment]
Not all months are 31 days, if you literally want to add 31 days to the first of a month:
Source: Add day(s) to a Date object
var myDate = new Date();
myDate.setDate(myDate.getDate() + AddDaysHere);
Where "AddDaysHere" would be 31.
If you just want to insure there is no way to select a date next month, you could:
// There is probably a billion better ways to get the next available month, this is just basic
let currentMonth = 2;
let nextMonth = currentMonth + 1;
if (nextMonth > 11) { nextMonth = 0;} // I believe javascript months start at 0.
Date(2018, nextMonth, 1)
Happy coding!
I am working on e2e using protractor. There is a scenario where I need to select one future date(10 days ahead from today), one past date(5days previous from today). If today's date is 12/20/2017 I need to select 12/30/2017 (future date) and 12/15/2017(past date) from two separate datepickers. I tried the below code, but everytime today's date is getting selected even though future date is specified by adding the number of days(10). Future date is correctly printed on console, but it is selecting today's date from the datepicker. Please let me how to do this.
function consentEffectiveDate(){
var picker = element(by.model('case.consentEffectiveDate'));
// get today's date
var today = new Date();
var dd = today.getDate()+10;
console.log("date: "+dd);
var mm = today.getMonth() + 1; //January is 0!
var yyyy = today.getFullYear();
if (dd < 10) {
dd = '0' + dd
}
if (mm < 10) {
mm = '0' + mm
}
today = mm + '/' + dd + '/' + yyyy;
picker.sendKeys(today);
console.log("date:"+today);
Thanks in advance for any help.
html code
<input type="text" readonly="readonly"
class="form-control effectiveDate ng-pristine ng-valid ng-valid-pattern ng-touched"
name="effectiveDate" id="effectiveDate"
ng-model="case.consentEffectiveDate" placeholder="MM/DD/YYYY"
ng-pattern="/^([0]?\d{1}|[1][0-2])\/(([0-2]?\d{1})|([3][0,1]{1}))\/(([1]{1}[9]{1}[9]{1}\d{1})|([1-9]{1}\d{3}))$/"
data-ng-change="model.compareDates(case.consentEffectiveDate, case.consentExpiresDate, new_consent);"
ng-class="{ 'has-error' : new_consent.effectiveDate.$invalid && (new_consent.effectiveDate.$dirty || submitted)}"
style="">
I experienced the same issue before. For me it was that the date-picker wasn't focused by protractor and therefore the date wasn't sent to the input field.
Try focusing the element by clicking it first and then pass the keys.
var picker = element(by.model('case.consentEffectiveDate'));
picker.click().sendKeys(today);
If there is a possibility that the date is pre-filled, you could write it like this to remove the previous date from the picker before entering the new date.
picker.click().sendKeys(protractor.Key.CONTROL, "a", protractor.Key.NULL, today);
Hope this helps
i'm using md-select to pick a year there is a scenario that when you fill up the form in the first time you will get a default value of latest year else you will get the previous value.
here's my view(slim format)
md-input-container flex=""
label Year
md-select name="type" ng-model="detail.year" ng-change="addYear(detail.product_id)"
md-option ng-repeat="year in years" value="{{year.year}}" ng-selected="detail.year? == null ? year.year : $first"
| {{year.year}}
and here's my controller for iterate the year (coffee format)
$scope.years = []
start_year = (new Date).getFullYear()
i = start_year
while i >= 2005
$scope.years.push(year: i)
i--
my error
putting comment as answer...
ng-selected="detail.year? == null ? year.year : $first" | {{year.year}}
don't add logic in html, keep it in JS files, it will be more easily testable + you dont have to fight with angular syntax support
Hi I am new in angular and making my first module. This article is very helpfull. I want to filter my data by lastweek records. I have already found days by current date and given date in mysql query, On button click I am just setting value like DisTopic=1 and this works fine.
May you please tell me how can I apply filter for a range like day>=1 && day<=7
I am using below:-
filter:{'topic': DisTopic,'attachment':attch, 'days':day}
Please help me.
Solution 1: with angular-filter module
As stated by other users, you could indeed do that with a custom filter. However, if you find yourself writing a lot of custom filters, I'll advise you have a look at angular-filter module. With this module you can do what you need with the pick filter :
<div ng-repeat="task in tasks | pick: 'days >= 1 && days <= 7'">{{task.name}}</div>
See demo fiddle
Solution 2: Custom filter with parameters
Template:
<div ng-repeat="task in tasks | dayFilter: 1 : 7">{{task.name}}</div>
Javascript:
app.filter('dayFilter', function() {
return function(input, startDay, endDay) {
var filterFunction = function (item) {
return item.days >= startDay && item.days <= endDay;
};
return input.filter(filterFunction);
};
});
See updated demo fiddle
Custom filter example, you can modify as per your need.
Controller
$scope.search = function (item) {
if ($scope.searchUser == null || $scope.searchUser.trim() == "")
return true;
if (item.FirstName.toLowerCase().indexOf($scope.searchUser.toLowerCase()) != -1 || item.LastName.toLowerCase().indexOf($scope.searchUser.toLowerCase()) != -1 || item.Role.toLowerCase().indexOf($scope.searchUser.toLowerCase()) != -1) {
return true;
}
return false;
};
and than call it in your view
| filter:search
So, depending on your requirement, you can pass as many parameters and modify method in controller.
//Below code solve my problem.
Date.prototype.getWeek = function () {
// Create a copy of this date object
var target = new Date(this.valueOf());
// ISO week date weeks start on monday
// so correct the day number
var dayNr = (this.getDay() + 6) % 7;
// ISO 8601 states that week 1 is the week
// with the first thursday of that year.
// Set the target date to the thursday in the target week
target.setDate(target.getDate() - dayNr + 3);
// Store the millisecond value of the target date
var firstThursday = target.valueOf();
// Set the target to the first thursday of the year
// First set the target to january first
target.setMonth(0, 1);
// Not a thursday? Correct the date to the next thursday
if (target.getDay() !== 4) {
target.setMonth(0, 1 + ((4 - target.getDay()) + 7) % 7);
}
// The weeknumber is the number of weeks between the
// first thursday of the year and the thursday in the target week
return Math.ceil((firstThursday - target) / 604800000) - 1; // 604800000 = 7 * 24 * 3600 * 1000
};