How to add extra class with easepick - javascript

Please Help! How to add "myCss" class for one date before bookedDates? (17 Aug and 17 Sep in my example). The idea is to paint a different color day before booked.
This is example code for which I am trying to do this:
const DateTime = easepick.DateTime;
const bookedDates = [
'18-08-2022', '19-08-2022', '20-08-2022', '18-09-2022', '19-09-2022', '20-09-2022',
].map(d => {
if (d instanceof Array) {
const start = new DateTime(d[0], 'DD-MM-YYYY');
const end = new DateTime(d[1], 'DD-MM-YYYY');
return [start, end];
}
return new DateTime(d, 'DD-MM-YYYY');
});
const picker = new easepick.create({
element: document.getElementById('datepicker'),
css: [
'https://cdn.jsdelivr.net/npm/#easepick/bundle#1.2.0/dist/index.css',
'https://easepick.com/css/demo_hotelcal.css',
],
readonly: true,
zIndex: 10,
format: "DD MMM YYYY",
readonly: false,
plugins: ['RangePlugin', 'LockPlugin'],
RangePlugin: {
tooltipNumber(num) {
return num - 1;
},
locale: {
one: 'night',
other: 'nights',
},
},
LockPlugin: {
minDate: new Date(),
minDays: 2,
inseparable: true,
filter(date, picked) {
if (picked.length === 1) {
const incl = date.isBefore(picked[0]) ? '[)' : '(]';
return !picked[0].isSame(date, 'day') && date.inArray(bookedDates, incl);
}
return date.inArray(bookedDates, '[)');
},
}
});
<script src="https://cdn.jsdelivr.net/npm/#easepick/bundle#1.2.0/dist/index.umd.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/#easepick/bundle#1.2.0/dist/index.umd.min.js"></script>
<input readonly="readonly" id="datepicker"/>

You need to use a setup option in easepick.create({ ... }):
Before date
setup(picker) {
picker.on('view', (event) => {
const { view, target, date } = event.detail;
if (view === 'CalendarDay') {
const dayAfter = date.clone().add(1, 'day');
if (
! picker.options.LockPlugin.filter(date, picker.datePicked)
&& picker.options.LockPlugin.filter(dayAfter, picker.datePicked)
) {
target.classList.add('myCss');
}
}
});
},
After date
setup(picker) {
picker.on('view', (event) => {
const { view, target, date } = event.detail;
if (view === 'CalendarDay') {
const dayBefore = date.clone().subtract(1, 'day');
if (
picker.options.LockPlugin.filter(dayBefore, picker.datePicked)
&& ! picker.options.LockPlugin.filter(date, picker.datePicked)
) {
target.classList.add('myCss');
}
}
});
}

Related

JavaScript trying to find the highest sales made in a particular branch

I am trying to create a class to find out the branch made the most in revenue.I believe, I need to sum all branch across multiple days and identify which branch had the highest sales overall. But I am kinda lost. Would anyone be able to help me? Thanks for the help
class SalesItem {
constructor(branch, totalSales, date) {
this.branch = branch;
this.totalSales = totalSales;
this.date = date
}
}
function CalculateBestBranch(sales) {
var branchSales = { key: "", value: 0 };
// TODO: order branchSales by value, highest first
// TODO: return the key of the highest value
const highestValue = 0;
return highestValue;
}
class SalesItem {
constructor(branch, totalSales, date) {
this.branch = branch;
this.totalSales = totalSales;
this.date = date;
}
}
const sales = [
new SalesItem('branch-1', 60, '2022-01-26'),
new SalesItem('branch-2', 90, '2022-01-26'),
new SalesItem('branch-1', 20, '2022-01-27'),
new SalesItem('branch-2', 30, '2022-01-27'),
];
function calculateBestBranch(sales) {
const branchSales = [];
sales.forEach((sale) => {
if (!branchSales.find((e) => e.key === sale.branch)) {
branchSales.push({ key: sale.branch, value: sale.totalSales });
} else {
let i = branchSales.findIndex((e) => e.key == sale.branch);
branchSales[i].value += sale.totalSales;
}
});
const sortedBranchSales = branchSales.sort((a, b) => b.value - a.value);
return sortedBranchSales[0];
}
calculateBestBranch(sales); // { key: 'branch-2', value: 120 }

Deprecation warning: value provided is not in a recognized RFC2822 or ISO

moment.min.js:6 Deprecation warning: value provided is not in a recognized RFC2822 or ISO format. moment construction falls back to js Date(), which is not reliable across all browsers and versions. Non RFC2822/ISO date formats are discouraged and will be removed in an upcoming major release. Please refer to http://momentjs.com/guides/#/warnings/js-date/ for more info.
Arguments:
[0] _isAMomentObject: true, _isUTC: false, _useUTC: false, _l: undefined, _i: 07/07/2021 12:00 AM, _f: undefined, _strict: undefined, _locale: [object Object]
Error
at Function.createFromInputFallback (https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js:6:3248)
at gb (https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js:6:19736)
at rb (https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js:6:22824)
at qb (https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js:6:22691)
at pb (https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js:6:22410)
at sb (https:///ajax/libs/moment.js/2.18.1/moment.min.js:6:23150)
at tb (https:///ajax/libs/moment.js/2.18.1/moment.min.js:6:23184)
at a (https:///ajax/libs/moment.js/2.18.1/moment.min.js:6:202)
at HTMLButtonElement.eval (webpack:///./Scripts/calendar.js?:97:19)
at HTMLButtonElement.dispatch (https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js:2:41772)
Hi, i have this problem with my asp.net-core project. I try to copy this scheduler: https://github.com/esausilva/fullcalendar-aspnet-core
but...
My js code is this:
let currentEvent;
const formatDate = date => date === null ? '' : moment(date).format("MM/DD/YYYY h:mm A");
const fpStartTime = flatpickr("#StartTime", {
enableTime: true,
dateFormat: "m/d/Y h:i K"
});
const fpEndTime = flatpickr("#EndTime", {
enableTime: true,
dateFormat: "m/d/Y h:i K"
});
$('#calendar').fullCalendar({
defaultView: 'month',
height: 'parent',
header: {
left: 'prev,next today',
center: 'title',
right: 'month,agendaWeek,agendaDay'
},
eventRender(event, $el) {
$el.qtip({
content: {
title: event.title,
text: event.description
},
hide: {
event: 'unfocus'
},
show: {
solo: true
},
position: {
my: 'top left',
at: 'bottom left',
viewport: $('#calendar-wrapper'),
adjust: {
method: 'shift'
}
}
});
},
events: '/Calendar/GetCalendarEvents',
eventClick: updateEvent,
selectable: true,
select: addEvent
});
/**
* Calendar Methods
**/
function updateEvent(event, element) {
currentEvent = event;
if ($(this).data("qtip")) $(this).qtip("hide");
$('#eventModalLabel').html('Edit Event');
$('#eventModalSave').html('Update Event');
$('#EventTitle').val(event.title);
$('#Description').val(event.description);
$('#isNewEvent').val(false);
const start = formatDate(event.start);
const end = formatDate(event.end);
fpStartTime.setDate(start);
fpEndTime.setDate(end);
$('#StartTime').val(start);
$('#EndTime').val(end);
if (event.allDay) {
$('#AllDay').prop('checked', 'checked');
} else {
$('#AllDay')[0].checked = false;
}
$('#eventModal').modal('show');
}
function addEvent(start, end) {
$('#eventForm')[0].reset();
$('#eventModalLabel').html('Add Event');
$('#eventModalSave').html('Create Event');
$('#isNewEvent').val(true);
start = formatDate(start);
end = formatDate(end);
fpStartTime.setDate(start);
fpEndTime.setDate(end);
$('#eventModal').modal('show');
}
/**
* Modal
* */
$('#eventModalSave').click(() => {
const title = $('#EventTitle').val();
const description = $('#Description').val();
const startTime = moment($('#StartTime').val());
const endTime = moment($('#EndTime').val());
const isAllDay = $('#AllDay').is(":checked");
const isNewEvent = $('#isNewEvent').val() === 'true' ? true : false;
if (startTime > endTime) {
alert('Start Time cannot be greater than End Time');
return;
} else if ((!startTime.isValid() || !endTime.isValid()) && !isAllDay) {
alert('Please enter both Start Time and End Time');
return;
}
const event = {
title,
description,
isAllDay,
startTime: startTime._i,
endTime: endTime._i
};
if (isNewEvent) {
sendAddEvent(event);
} else {
sendUpdateEvent(event);
}
});
function sendAddEvent(event) {
axios({
method: 'post',
url: '/CalendarController/AddEvent',
data: {
"Title": event.title,
"Description": event.description,
"Start": event.startTime,
"End": event.endTime,
"AllDay": event.isAllDay
}
})
.then(res => {
const { message, eventId } = res.data;
if (message === '') {
const newEvent = {
start: event.startTime,
end: event.endTime,
allDay: event.isAllDay,
title: event.title,
description: event.description,
eventId
};
$('#calendar').fullCalendar('renderEvent', newEvent);
$('#calendar').fullCalendar('unselect');
$('#eventModal').modal('hide');
} else {
alert(`Something went wrong: ${message}`);
}
})
.catch(err => alert(`Something went wrong: ${err}`));
}
function sendUpdateEvent(event) {
axios({
method: 'post',
url: '/Calendar/UpdateEvent',
data: {
"EventId": currentEvent.eventId,
"Title": event.title,
"Description": event.description,
"Start": event.startTime,
"End": event.endTime,
"AllDay": event.isAllDay
}
})
.then(res => {
const { message } = res.data;
if (message === '') {
currentEvent.title = event.title;
currentEvent.description = event.description;
currentEvent.start = event.startTime;
currentEvent.end = event.endTime;
currentEvent.allDay = event.isAllDay;
$('#calendar').fullCalendar('updateEvent', currentEvent);
$('#eventModal').modal('hide');
} else {
alert(`Something went wrong: ${message}`);
}
})
.catch(err => alert(`Something went wrong: ${err}`));
}
$('#deleteEvent').click(() => {
if (confirm(`Do you really want to delte "${currentEvent.title}" event?`)) {
axios({
method: 'post',
url: '/Calendar/DeleteEvent',
data: {
"EventId": currentEvent.eventId
}
})
.then(res => {
const { message } = res.data;
if (message === '') {
$('#calendar').fullCalendar('removeEvents', currentEvent._id);
$('#eventModal').modal('hide');
} else {
alert(`Something went wrong: ${message}`);
}
})
.catch(err => alert(`Something went wrong: ${err}`));
}
});
$('#AllDay').on('change', function (e) {
if (e.target.checked) {
$('#EndTime').val('');
fpEndTime.clear();
this.checked = true;
} else {
this.checked = false;
}
});
$('#EndTime').on('change', () => {
$('#AllDay')[0].checked = false;
});

Bootstrap datepicker set dates when creating the datepicker

I've an issue with the bootstrap datepicker: I need to set dates when instantiating the datepicker, without triggering the dateChange event. The reason is that I'm listening to the datechange event to submit a form, so I can't trigger it for setting the selected dates.
I need to be able to set the two days selected from data I store in a div
const $picker = $('.datetimepicker2').datepicker({
inline: true,
multidate: 2,
debug: true,
format: 'dd/mm/yy',
beforeShowDay: function(date) {
if($picker && $picker.datepicker('getDates').length === 2) {
const selectedDates = $picker.datepicker('getDates');
const startDate = moment(selectedDates[0]);
const endDate = moment(selectedDates[1]);
const day = moment(date);
if(day.isAfter(startDate) && day.isBefore(endDate)) {
return {
enabled: true,
classes: 'active'
}
}
}
}
}).on('changeDate', (event) => {
const startDate = moment(event.dates[0]).format('DD/MM/YY');
const $form = $('.main_search').find('form');
const $input = $('<input>', { name: 'start_date', value: startDate , type: 'hidden'});
$form.append($input);
$form.submit();
});
The problem is that if I set dates with this code, it will submit the form
const homeData = $('#home-data').data();
if( homeData.startDate ) {
let dates = [];
dates.push(homeData.startDate);
$picker.datepicker('setDates', dates);
}

how to change NgbDatePicker format from YYYY-MM-DD to MM-DD-YYYY angular 4?

hi i am using ngbDatePicker and my format is YYYY-MM-DD
and i am trying to change it but cant seem to change the format to MM/DD/YYYY.
here is my html code
<div class="form-group datepicker">
<label for="dob">Date of Birth*</label>
<div class="row input-group">
<input
ngbDatepicker
#d="ngbDatepicker"
#dobF="ngModel"
class="form-control input-underline input-lg"
id="dob"
[(ngModel)]="dateOfBirth"
placeholder="mm-dd-yyyy"
name="dp"
[ngClass]="{
invalid:
(dobF.value === null || isString(dobF.value) || futureDate) && dobF.touched
}"
required
/>
<div class="input-group-append">
<button
class="btn btn-outline-secondary calendar"
(click)="d.toggle()"
type="button"
></button>
</div>
</div>
<div
*ngIf="
(dobF.value === null || isString(dobF.value) || futureDate) && dobF.touched
"
class="error"
>
Please enter a valid date of birth.
</div>
</div>
here is my ts file code
public dateOfBirth: { year: number; month: number; day: number };
public currentDate = moment().format("YYYY-MM-DD");
constructor(
private config: NgbDatepickerConfig
) {
// customize default values of datepickers used by this component tree
const currentDate = new Date();
const day = currentDate.getDate();
const month = currentDate.getMonth() + 1;
const year = currentDate.getFullYear();
this.config.minDate = {year: 1900, month: 1, day: 1};
this.config.maxDate = {year, month, day};
this.config.outsideDays = "hidden";
}
ngOninit() {
this.subscriptions["patient"] = this.store
.select("patient")
.subscribe(data => {
this.patient = Object.assign({}, this.patient, data);
const dob = this.patient.Dob ? this.patient.Dob.split("-") : null;
dob !== null
? (this.dateOfBirth = {
year: Number(dob[0]),
month: Number(dob[1]),
day: Number(dob[2])
})
: (this.dateOfBirth = null);
});
}
ngAfterContentChecked() {
let currentDateObject = this.currentDate.split("-");
this.dobYear = Number(currentDateObject[0]);
this.dobMonth = Number(currentDateObject[1]);
this.dobDay = Number(currentDateObject[2]);
if (this.dateOfBirth) {
this.futureDate = this.dateOfBirth.year > this.dobYear || (this.dateOfBirth.year == this.dobYear && this.dateOfBirth.month > this.dobMonth)
|| (this.dateOfBirth.year == this.dobYear && this.dateOfBirth.month == this.dobMonth && this.dateOfBirth.day > this.dobDay);
}
}
i cannot seem to find any help to change the format.
how can i change the format from YYYY/DD/MM toMM/DD/YYYY.
is there any help thanks
You need to extend NgbDateParserFormatter and override the default provider:
Below is an example for dd/mm/yyyy, you'll just need to alter the parse() and format() functions to change to mm/dd/yyyy.
Add the following class:
import { NgbDateParserFormatter, NgbDateStruct } from "#ng-bootstrap/ng-bootstrap";
import { Injectable } from "#angular/core";
#Injectable()
export class NgbDateCustomParserFormatter extends NgbDateParserFormatter {
parse(value: string): NgbDateStruct {
if (value) {
const dateParts = value.trim().split("/");
if (dateParts.length === 1 && isNumber(dateParts[0])) {
return { day: toInteger(dateParts[0]), month: null, year: null };
} else if (dateParts.length === 2 && isNumber(dateParts[0]) && isNumber(dateParts[1])) {
return {
day: toInteger(dateParts[0]),
month: toInteger(dateParts[1]),
year: null
};
} else if (dateParts.length === 3 && isNumber(dateParts[0]) && isNumber(dateParts[1]) && isNumber(dateParts[2])) {
return {
day: toInteger(dateParts[0]),
month: toInteger(dateParts[1]),
year: toInteger(dateParts[2])
};
}
}
return null;
}
format(date: NgbDateStruct): string {
return date
? `${isNumber(date.day) ? padNumber(date.day) : ""}/${isNumber(date.month) ? padNumber(date.month) : ""}/${
date.year
}`
: "";
}
}
export function toInteger(value: any): number {
return parseInt(`${value}`, 10);
}
export function isNumber(value: any): value is number {
return !isNaN(toInteger(value));
}
export function padNumber(value: number) {
if (isNumber(value)) {
return `0${value}`.slice(-2);
} else {
return "";
}
}
Modify app.module.ts to override the default provider:
import { NgbDateCustomParserFormatter } from "./YOURPATH/date-formatter.service";
#NgModule({
declarations: [
...
],
imports: [
...
],
providers: [
... ,
{ provide: NgbDateParserFormatter, useClass: NgbDateCustomParserFormatter } // <-- add this
],
bootstrap: [AppComponent]
})
export class AppModule {}
The perfect solution would be to alter the file below, I have edited the code to get the required format(DD-MM-YYYY) in my input field.
ngb-date-parser-formatter.js
from the code below you will get DD-MM-YYYY Date format in input filed.
var __extends = (this && this.__extends) || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
import { padNumber, toInteger, isNumber } from '../util/util';
/**
* Abstract type serving as a DI token for the service parsing and formatting dates for the NgbInputDatepicker
* directive. A default implementation using the ISO 8601 format is provided, but you can provide another implementation
* to use an alternative format.
*/
var NgbDateParserFormatter = (function () {
function NgbDateParserFormatter() {
}
return NgbDateParserFormatter;
}());
export { NgbDateParserFormatter };
var NgbDateISOParserFormatter = (function (_super) {
__extends(NgbDateISOParserFormatter, _super);
function NgbDateISOParserFormatter() {
return _super !== null && _super.apply(this, arguments) || this;
}
NgbDateISOParserFormatter.prototype.parse = function (value) {
if (value) {
var dateParts = value.trim().split('-');
if (dateParts.length === 1 && isNumber(dateParts[0])) {
return { year: toInteger(dateParts[0]), month: null, day: null };
}
else if (dateParts.length === 2 && isNumber(dateParts[0]) && isNumber(dateParts[1])) {
return { year: toInteger(dateParts[0]), month: toInteger(dateParts[1]), day: null };
}
else if (dateParts.length === 3 && isNumber(dateParts[0]) && isNumber(dateParts[1]) && isNumber(dateParts[2])) {
return { year: toInteger(dateParts[0]), month: toInteger(dateParts[1]), day: toInteger(dateParts[2]) };
}
}
return null;
};
NgbDateISOParserFormatter.prototype.format = function (date) {
return date ?
(isNumber(date.day) ? padNumber(date.day) : '')+"-"+ (isNumber(date.month) ? padNumber(date.month) : '') +"-"+ date.year:'';
};
return NgbDateISOParserFormatter;
}(NgbDateParserFormatter));
export { NgbDateISOParserFormatter };
//# sourceMappingURL=ngb-date-parser-formatter.js.map

Pikaday.js: How to disbale days in calendar?

I have a calendar and I want to set a few days to disable. Does anyone have experience with this? On github it says:
disableDayFn: callback function that gets passed a Date object for each day in view. Should return true to disable selection of that day.
But how can I use this?
var bookingPicker = new Pikaday(
{
field: $(self.options.calendarInput, container)[0],
container: $(self.options.calendarContainer, container)[0],
minDate: new Date(),
bound: false,
firstDay: 1,
onOpen: function () {
this.disableDayFn(23); //<--- ???
},
onSelect: function (date) {
},
onDraw: function (date) {
console.log("NEW MONTH")
}
}
);
var bookingPicker = new Pikaday(
{
field: $(self.options.calendarInput, container)[0],
container: $(self.options.calendarContainer, container)[0],
minDate: new Date(),
bound: false,
firstDay: 1,
onOpen: function () {
this.disableDayFn(23); //<--- ???
},
onSelect: function (date) {
},
onDraw: function (date) {
console.log("NEW MONTH")
},
disableDayFn: function(dateTime){
/* here you can access each day shown and disable those in your range. To disable just return true*/
}
}
);
So every date you can see on the picker is passed, just do whatever checks you want in the function against that date. Here's an example using a string array of dates that uses moment.js to qualify equality.
var validDateArray = ["2017-JAN-01", "2017-JAN-02", "2017-JAN-03"]
in the picker:
disableDayFn: (dateToCheck: Date) => {
if (validDateArray == undefined) {
console.log("...validDateArray == undefined");
return true;
}
let d1 = Moment(dateToCheck).format("YYYY-MMM-DD");
for (let d2 of validDateArray) {
if (d1 == d2) {
console.log("...date is valid");
return false;
}
}
console.log("...date is not valid");
return true;
}

Categories