Firebase OrderByChild Timestamp not working - javascript

I am using a datepicker to retrieve an object from my Firebase DB, it works but no matter which date I select, today's object is returned.
I am using orderByChild and timestamp to sort, but it is not working.
var ref = firebase.database().ref(uid);
ref.orderByChild('timestamp').startAt(strDateTime).endAt(strDateTime + "86400").on('value', function (snapshot) {
snapshot.forEach(function (childSnapshot) {
// childData will be the actual contents of the child
var childData = childSnapshot.val();
arms = childData.arms;
console.log(arms);
document.getElementById("demo").innerHTML = arms;
});
});
My database structure is:
{
"ZwYo0nB92oODcjjxJ0Eqeo4l3Ny1" : {
"BodyStats-KaFX2MvLHt0U6lLc365" : {
"arms" : "48",
"bodyfat" : "",
"calves" : "",
"chest" : "",
"forearms" : "",
"hips" : "",
"neck" : "",
"shoulders" : "",
"thighs" : "",
"timestamp" : 1484188562973,
"waist" : "",
"weight" : ""
}
}
}
The strDateTime:
// Date Picker Function
var strDateTime;
var timeInt;
$(function () {
$('#datepicker').datepicker({
inline: false, // Expanded cal
//nextText: '→',
//prevText: '←',
showOtherMonths: true,
//dateFormat: 'dd MM yy',
dayNamesMin: ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'],
showOn: "button",
buttonImage: "img/calendar-icon.png",
buttonImageOnly: true,
onSelect: function () { // When cal is opened execute
var currentDate = new Date($("#datepicker").datepicker("getDate"));
var strDateTime = currentDate.getDate() + "/" + (currentDate.getMonth() + 1) + "/" + currentDate.getFullYear();
alert(strDateTime);
startDatabaseQueries(strDateTime);
var timeInt = parseInt(strDateTime); // Parse strDateTime for startDatabaseQueries function
}
});
$('#datepicker').datepicker('setDate', new Date());
var currentDate = new Date($("#datepicker").datepicker("getDate"));
var strDateTime = currentDate.getDate() + "/" + (currentDate.getMonth() + 1) + "/" + currentDate.getFullYear();
});

Related

How to set second litepicker startDate based on first litepicker startDate selection

Hey my fellow Stackoverflowers, I am working with litepicker.js and ran into a snag that I am hoping one of you can help me figure out.
I have built out two separate litepickers and am successfully populating todays date on the first and tomorrows date in the second. (these are also successfully being accepted as the minDate for both)
What I have not been able to figure out is how to set the minDate for the second litepicker to one day after the selected startDate of the first litepicker.
You can see where I am at in this codepen
https://codepen.io/DigitalDesigner/pen/oNGRWzV
HTML Code:
<form>
<input id="start-date" class="form-control start-date"> /
<input id="end-date" class="form-control end-date">
</form>
Javascript:
<script>
let current = new Date();
let tomorrow = new Date(current.getTime() + 86400000); // + 1 day in ms
tomorrow.toLocaleDateString();
// Add litepicker calendar to stay dates
const startpicker = new Litepicker({
element: document.getElementById('start-date'),
singleMode: true,
allowRepick: true,
autoRefresh: true,
format: 'D MMMM YYYY',
startDate: current,
minDate: new Date(),
numberOfMonths: 1,
numberOfColumns: 1,
tooltipText: {
one: 'night',
other: 'nights'
},
tooltipNumber: (totalDays) => {
return totalDays - 1;
},
plugins: ['mobilefriendly']
});
const endpicker = new Litepicker({
element: document.getElementById('end-date'),
singleMode: true,
allowRepick: true,
autoRefresh: true,
format: 'D MMMM YYYY',
startDate: tomorrow,
minDate: current,
numberOfMonths: 1,
numberOfColumns: 1,
tooltipText: {
one: 'night',
other: 'nights'
},
tooltipNumber: (totalDays) => {
return totalDays - 1;
},
});
</script>
here is the litepicker site: https://litepicker.com/
How can I set the minDate for the second litepicker based on the first litepickers selected date?
Thanks in advance.
add this to the code
startpicker.on('selected', (date1, date2) => {
endpicker.setOptions({
minDate: startpicker.getDate(),
startDate: startpicker.getDate()
});
});

How to set maxDate is last day of december on current year?

I have this date range datepicker :
$(function () {
//date picker range
$(function () {
var dateFormat = "mm/dd/yy",
from = $("#<%= TextBox1.ClientID %>").datepicker({
//defaultDate: "+1w",
changeMonth: true,
minDate: MinDateManipulation(),
beforeShowDay: DisableMonday,
maxDate: '+2M',
numberOfMonths:1
})
.on("change", function () {
to.datepicker("option", "minDate", getDate(this));
}),
to = $("#<%= TextBox2.ClientID %>").datepicker({
//defaultDate: "+1w",
changeMonth: true,
beforeShowDay: DisableMonday,
maxDate: '+2M',
numberOfMonths:1
})
.on("change", function () {
from.datepicker("option", "maxDate", getDate(this));
});
function getDate(element) {
var date;
try {
date = $.datepicker.parseDate(dateFormat, element.value);
} catch (error) {
date = null;
}
return date;
}
});
It work when i tried to disable date from 2 months after current date, but the purpose is, to disable date in January 1st every next year after current year.
for example : current date [11/3/2018]
I want to disable date to chose after last day of December every current year, with maxDate [31/12/2018].
But how do we set dynamically for the value of the maxDate? without update the value of the year manually with my daterange condition script?
It's not clear the range you are trying to capture, yet you can do a lot with what you already have.
One way would be to set it to a string format:
var yr = $.datepicker.formatDate("yy", new Date());
var dec31 = "12/31/" + yr;
....({
maxDate: dec31,
})
this will get the current Year (2018) and create a string that can be used as the max date: 12/31/2018. This will remain dynamic and update each year.
You could also define a number of days in the year as holidays. Lots of things you can do.
Maybe this example will help clear up a few things.
$(function() {
var holidays = {
2018: {
11: {
12: [
false,
"holiday",
"Veterans Day Observed"
],
22: [
false,
"holiday",
"Thanksgiving Day"
]
},
12: {
25: [
false,
"holiday",
"Christmas Day"
],
31: [
false,
"holiday",
"New Year's Eve"
]
}
},
2019: {
1: {
1: [
false,
"holiday",
"New Year's Day"
],
21: [
false,
"holiday",
"Martin Luther King Jr. Day"
]
},
2: {
18: [
false,
"holiday",
"Presidents' Day"
]
},
5: {
27: [
false,
"holiday",
"Memorial Day"
]
},
7: {
4: [
false,
"holiday",
"Independence Day"
]
},
9: {
2: [
false,
"holiday",
"Labor Day"
]
},
10: {
14: [
false,
"holiday",
"Columbus Day"
]
},
11: {
11: [
false,
"holiday",
"Veterans Day"
],
28: [
false,
"holiday",
"Thanksgiving Day"
]
},
12: {
25: [
false,
"holiday",
"Christmas Day"
],
31: [
false,
"holiday",
"New Year's Eve"
]
}
}
};
function disableDays(d) {
var result = [true, ""];
var yr = $.datepicker.formatDate("yy", d),
mo = $.datepicker.formatDate("m", d),
dy = $.datepicker.formatDate("d", d);
if ($.datepicker.formatDate("D", d) == "Mon") {
result[0] = false;
}
if (holidays[yr] !== undefined) {
if (holidays[yr][mo] !== undefined) {
if (holidays[yr][mo][dy] !== undefined) {
console.log("Holiday:", yr, mo, dy);
result = holidays[yr][mo][dy];
}
}
}
return result;
}
var dateFormat = "mm/dd/yy",
from = $("#client-id-1").datepicker({
//defaultDate: "+1w",
changeMonth: true,
minDate: 0,
beforeShowDay: disableDays,
maxDate: '+1y',
numberOfMonths: 1
})
.on("change", function() {
to.datepicker("option", "minDate", getDate(this));
}),
to = $("#client-id-2").datepicker({
//defaultDate: "+1w",
changeMonth: true,
beforeShowDay: disableDays,
maxDate: '+2m',
numberOfMonths: 1
})
.on("change", function() {
from.datepicker("option", "maxDate", getDate(this));
});
function getDate(element) {
var date;
try {
date = $.datepicker.parseDate(dateFormat, element.value);
} catch (error) {
date = null;
}
return date;
}
});
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<p>Client 1: <input type="text" id="client-id-1"></p>
<p>Client 2: <input type="text" id="client-id-2"></p>
You can use moment.js and use my code to get max date:
function _getMaxDate() {
const today = moment().startOf('day')
const lastDayOfYear = moment().endOf('year').startOf('day')
return lastDayOfYear.diff(today, 'days')
}

How to disable occupied dates in daterangepicker JS and Laravel

I'm trying to implement a resort booking where I can check if a specific date is still available or not by using bootstrap daterangepicker but I can't figure out how to do this. I got this thread but it is not using daterangepicker.
Note: I'm also using laravel5.1 so maybe this can help the problem.
Database fields
id
name
Place
start_time
end_time
My JS Code Setup with daterangepicker
$(function () {
$('.time').daterangepicker({
"minDate": moment('{{ date('Y-m-d G') }}'),
"timePicker": true,
"showDropdowns": true,
"timePicker24Hour": false,
"timePickerIncrement": 5,
"autoApply": true,
"locale": {
"format": "MM/DD/YYYY hh:mm:ss A",
"separator": " — ",
}
});
});
You want to ideally, use the isInvalidDate configuration option when creating a new instance of the daterangepicker.
isInvalidDate
var disabledDates = {{ $disabledDates->toJson(); }};
$(function () {
$('.time').daterangepicker({
"minDate": moment('{{ date('Y-m-d G') }}'),
"timePicker": true,
"showDropdowns": true,
"timePicker24Hour": false,
"timePickerIncrement": 5,
"autoApply": true,
"locale": {
"format": "MM/DD/YYYY hh:mm:ss A",
"separator": " — ",
},
"isInvalidDate": function (date) {
return disabledDates.indexOf(date) != -1;
}
});
});
The $disabledDates php variable in this instance, is assumed to be a collection of disabled dates, all as their string formats.
Assume you have a start_date and a end_date.
$(function() {
var start_date = '2018-3-1';
var end_date = '2018-3-10';
$('input[name="daterange"]').daterangepicker({
"minDate": moment('2018-1-1'),
"timePicker": true,
"showDropdowns": true,
"timePicker24Hour": false,
"timePickerIncrement": 5,
"autoApply": true,
"locale": {
"format": "MM/DD/YYYY hh:mm:ss A",
"separator": " — ",
},
"isInvalidDate": function (date) {
var is_valid = true;
#foreach($dates as $date)
if(moment(date).isBetween($date->start_date, $date->end_date, 'day', '[]')){
is_valid = false;
}
#endforeach
return is_valid;
}
});
});
Then you can't select the day between start_date and end_date.

FullCalendar, business hours and date ranges

In my project, users can book rooms. My rooms have disponibility hours (eg 08:00-17:00). I try to use Business Hours but disponibilities change in summer and winter.
I also tried to use inverse-background events with date ranges like this post but if I use selectConstraint, the range is not taken in account.
The best would be to add date range to business hours, but it seems not implemented yet.
Has anyone a solution for my needs?
Thanks
edit: here is my fullcalendar options
function FCInit(){
var formatColumn, formatColumnWeek;
// Entete des colonnes
if ($(window).width() < 600) {
formatColumn = 'ddd';
formatColumnWeek = 'ddd\nDD/MM';
}
else {
formatColumn = 'dddd';
formatColumnWeek = 'dddd\nDD/MM';
}
var fcOpts = {
header: {
left: 'today,datePickerButton',
center: 'prev,title,next',
right: 'month,agendaWeek,agendaDay'
},
contentHeight: 'auto',
eventLimit: false,
allDaySlot: true,
slotEventOverlap: false,
nowIndicator: true,
timeFormat: 'H:mm',
columnFormat: formatColumn, // Format des jours dans l'entete ddd: Mon / ddd M/D : Mon 09/07 / dddd : MOnday /
navLinks: true,
eventOverlap: false,
selectable: true,
selectHelper: true,
selectOverlap: true,
selectConstraint:999,
unselectCancel: '#reservation',
views: {
week: {
columnFormat: formatColumnWeek
}
},
events:[{
id:3,
title:"R\u00e9serv\u00e9",
start:"2017-11-02 08:00",
end:"2017-11-02 10:00",
overlap:false,
color:"#C41305"
},{
id:999,
className:"fc-nonbusiness",
title:"",
start:"08:00",
end:"17:00",
dow:[4],
ranges:[
{
start:"2017-11-01",
end:"2017-11-30"
}
],
rendering:"inverse-background",
}],
/* Ajout de datepicker (nécessite Jquery UI css et js) */
customButtons: {
datePickerButton: {
text: '',
click: function () {
var $btnCustom = $('.fc-datePickerButton-button'); // name of custom button in the generated code
$btnCustom.after('<input type="hidden" id="hiddenDate" class="datepicker"/>');
$("#hiddenDate").datepicker({
flat: true,
showOn: "button",
dateFormat: "yy-mm-dd",
onSelect: function (dateText, inst) {
$('#full-calendar').fullCalendar('changeView', 'agendaDay', dateText);
}
});
var $btnDatepicker = $(".ui-datepicker-trigger"); // name of the generated datepicker UI
//Below are required for manipulating dynamically created datepicker on custom button click
$("#hiddenDate").show().focus().hide();
$btnDatepicker.trigger("click"); //dynamically generated button for datepicker when clicked on input textbox
$btnDatepicker.hide();
$btnDatepicker.remove();
$("input.datepicker").not(":first").remove();//dynamically appended every time on custom button click
}
}
},
dayRender: function(date, cell){
if(date.isBefore(new Date())){
cell.css('cursor','no-allowed');
}
},
eventRender: function (event, element) {
if(event.ranges) {
return (event.ranges.filter(function (range) { // test event against all the ranges
return (event.start.isBefore(range.end) &&
event.end.isAfter(range.start));
}).length) > 0;
}
if(event.rendering === "background"){
// Just add some text or html to the event element.
element.append("<div class='fc-title'>"+event.title+"</div>");
}
},
dayClick: function(date, jsEvent, view){
if(date.isSameOrAfter(new Date()) && view.name === 'month'){
$('#full-calendar').fullCalendar('changeView', 'agendaWeek', date);
}
},
select: function(start, end, jsEvent, view){
if(start.isSameOrAfter(new Date()) && view.name !== 'month'){
$('#reservation_dateFrom').val(start.format('DD/MM/YYYY HH:mm'));
$('#reservation_dateTo').val(end.format('DD/MM/YYYY HH:mm'));
$('#reservation').modal('show');
}else if(start.isBefore(new Date())){
alert('Il n\'est pas possible de réserver dans le passé');
$('#full-calendar').fullCalendar('unselect');
}
}
};
$('#full-calendar').fullCalendar(fcOpts);
};
and my symfony entities for storing the datas (where Horaire is a collection of business hours):
/*src/AppBundle/Entity/HoraireSalle.php*/
class HoraireSalle
{
/**
* #var int
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var \DateTime
*
* #ORM\Column(name="dateFrom", type="datetime")
*/
private $dateFrom;
/**
* #var \DateTime
*
* #ORM\Column(name="dateTo", type="datetime")
*/
private $dateTo;
/**
* #ORM\ManyToOne(targetEntity="Horaire", inversedBy="salles")
*/
private $horaire;
/**
* #ORM\ManyToOne(targetEntity="Salle", inversedBy="horaires")
*/
private $salle;
...
}
Thanks to #ADyson I do more or less what I want. Here is my solution.
function isAllowed(start, end) {
var events = $('#full-calendar').fullCalendar('clientEvents', function (event) {
return event.rendering === 'inverse-background' && event.start && event.end;
});
var allow = events.filter(function (event) {
return (start.isBetween(moment(new Date(event.ranges[0].start)), moment(new Date(event.ranges[0].end)))
&& end.isBetween(moment(new Date(event.ranges[0].start)), moment(new Date(event.ranges[0].end)))
&& start.format("HH:mm") >= event.start.format("HH:mm") && end.format("HH:mm") <= event.end.format("HH:mm")
&& event.dow.indexOf(start.day()) > -1
&& event.dow.indexOf(end.day()) > -1)
});
events = $('#full-calendar').fullCalendar('clientEvents', function (event) {
return event.rendering !== 'inverse-background' && event.start && event.end;
});
var overlap = events.filter(function (event) {
return event.start.isBefore(end) && event.end.isAfter(start);
});
if (allow.length && overlap.length == 0) {
return true;
}
return false;
}
function FCInit() {
var formatColumn, formatColumnWeek;
if ($(window).width() < 600) {
formatColumn = 'ddd';
formatColumnWeek = 'ddd\nDD/MM';
}
else {
formatColumn = 'dddd';
formatColumnWeek = 'dddd\nDD/MM';
}
var fcOpts = {
header: { // Ordre des boutons de l'entete
left: 'today,datePickerButton',
center: 'prev,title,next',
right: 'month,agendaWeek,agendaDay'
},
contentHeight: 'auto',
eventLimit: false,
allDaySlot: true,
slotEventOverlap: false,
nowIndicator: true,
timeFormat: 'H:mm',
columnFormat: formatColumn,
navLinks: true,
eventOverlap: false,
selectable: true,
selectHelper: true,
{% if businessHours is defined and businessHours is not empty %}
selectAllow: function (eventInfo) {
return isAllowed(eventInfo.start, eventInfo.end);
},
{% else %}
selectOverlap: false,
{% endif %}
unselectCancel: '#reservation',
views: {
week: {
columnFormat: formatColumnWeek
}
},
events: [{
id:3,
title:"R\u00e9serv\u00e9",
start:"2017-11-02 08:00",
end:"2017-11-02 10:00",
overlap:false,
color:"#C41305"
},{
id:999,
className:"fc-nonbusiness",
title:"",
start:"08:00",
end:"17:00",
dow:[4],
ranges:[
{
start:"2017-11-01",
end:"2017-11-30"
}
],
rendering:"inverse-background",
}],
/* Ajout de datepicker (nécessite Jquery UI css et js) */
customButtons: {
datePickerButton: {
text: '',
click: function () {
var $btnCustom = $('.fc-datePickerButton-button'); // name of custom button in the generated code
$btnCustom.after('<input type="hidden" id="hiddenDate" class="datepicker"/>');
$("#hiddenDate").datepicker({
flat: true,
showOn: "button",
dateFormat: "yy-mm-dd",
onSelect: function (dateText, inst) {
$('#full-calendar').fullCalendar('changeView', 'agendaDay', dateText);
}
});
var $btnDatepicker = $(".ui-datepicker-trigger"); // name of the generated datepicker UI
//Below are required for manipulating dynamically created datepicker on custom button click
$("#hiddenDate").show().focus().hide();
$btnDatepicker.trigger("click"); //dynamically generated button for datepicker when clicked on input textbox
$btnDatepicker.hide();
$btnDatepicker.remove();
$("input.datepicker").not(":first").remove();//dynamically appended every time on custom button click
}
}
},
dayRender: function (date, cell) {
if (date.isBefore(new Date())) {
cell.css('cursor', 'no-allowed');
}
},
eventRender: function (event, element, view) {
if (event.rendering === 'inverse-background' && event.ranges) {
return (event.ranges.filter(function (range) { // test event against all the ranges
var start = moment(new Date(range.start));
var end = moment(new Date(range.end));
return (view.start.isSameOrBefore(end) &&
view.end.isSameOrAfter(start)) &&
view.start.day(event.dow[0]).isBetween(start, end);
}).length > 0);
}
if (event.rendering === "background") {
// Just add some text or html to the event element.
$(element).data("title",event.title);
}
},
dayClick: function (date, jsEvent, view) {
if (date.isSameOrAfter(new Date()) && view.name === 'month') {
$('#full-calendar').fullCalendar('changeView', 'agendaWeek', date);
}
},
select: function (start, end, jsEvent, view) {
if (start.isSameOrAfter(new Date()) && view.name !== 'month') {
$('#reservation_dateFrom').val(start.format('DD/MM/YYYY HH:mm'));
$('#reservation_dateTo').val(end.format('DD/MM/YYYY HH:mm'));
$('#reservation').modal('show');
} else if (start.isBefore(new Date())) {
alert('Il n\'est pas possible de réserver dans le passé');
$('#full-calendar').fullCalendar('unselect');
}
}
};
$('#full-calendar').fullCalendar(fcOpts);
working example fullcalendar dynamic dow range
Suppose that you need to requiring event in between following date range
start: "2018-06-01",
end: "2018-08-01"
http://jsfiddle.net/521wucLq/

datepicker first date in array initial

The purpose of this code is to include only the dates within the array and to activate the first date as initial in the datepicker.
I was able to get the first key of the array, which in the case is the first date I need to be as initial.
I believe the problem is in the format of the date, since it is deconfiguring the datepicker.
Follow my code:
JAVASCRIPT
// datepicker
var availableDates = {
"19102017": [
"09:00",
"09:15",
"09:45",
"11:45",
"14:00"
],
"20102017": [
"09:30"
],
"21102017": [
"14:00"
],
"22102017": [
"11:45"
],
"23102017": [
"09:00"
],
"24102017": [
"09:15"
],
"25102017": [
"09:30"
],
"26102017": [
"09:45"
],
"27102017": [
"10:00"
],
"28102017": [
"10:15"
]
};
getMinDate(Object.keys(availableDates)[0]);
function returnavailableDates(){
return availableDates;
}
function getMinDate(date) {
console.log(date);
return date;
}
function checkDateis(d) {
var check = false;
$.each(availableDates, function( key, value ) {
if (d === key) {
check = true;
}
});
if(check) return true;
}
function available(date) {
var dmy = $.datepicker.formatDate('dmyy', date);
var check = checkDateis(dmy);
if (check) {
return [true, "", "Available"];
}
else {
return [false, "", "unAvailable"];
}
}
$("#datepicker").datepicker({
showOtherMonths : true,
selectOtherMonths : true,
minDate : 0,
nextText : '',
prevText : '',
dateFormat : 'dd-mm-yy',
beforeShowDay : available
})
.datepicker('setDate', getMinDate(Object.keys(availableDates)[0]))
fiddle for tests: https://jsfiddle.net/n2n4udkf/
Yes the problem is format of the date being passed to setDate.
You can fix the issue by formatting the date before passing it to setDate
function formatDate(date) {
return date.slice(0,2) + '-' + date.slice(2,4) + '-' + date.slice(4);
}
$("#datepicker").datepicker({
showOtherMonths : true,
selectOtherMonths : true,
minDate : 0,
nextText : '',
prevText : '',
dateFormat : 'dd-mm-yy',
beforeShowDay : available
})
.datepicker('setDate', formatDate(getMinDate(Object.keys(availableDates)[0])))
You should just change dateFormat in datepicker's init options:
$("#datepicker").datepicker({
...
dateFormat : 'ddmmyy',
...
})
Documentation: formatDate().
Added: Also, there is an error in available() function:
var dmy = $.datepicker.formatDate('dmyy', date);
It should be:
var dmy = $.datepicker.formatDate('ddmmyy', date);
It works now, because all of your date have two digits in both day and month components, but it will fail with dates like 01122017, for example: this function will produce 1122017 key and checkDateis(dmy) call will always return false.

Categories