Datetime-local set default hours - javascript

I'm using the following input :
<input id="creation-from-date" type="datetime-local"/>
I'd like know if there is a way to set default hours like this :
dd/mm/yyyy 00:00
Because the datepicker allows to pick date only, not time so I get an invalid date in JS side because the hours is not set.
I'm using Chrome v73.0.3683.75
Many thanks !

I would use <input type='date' /> and <input type='time' /> instead:
//<![CDATA[
/* external.js */
var doc, bod, I, DateTime; // for use on other loads
addEventListener('load', function(){
doc = document; bod = doc.body;
I = function(id){
return doc.getElementById(id);
}
DateTime = function(dateElement, timeElement, dateInstance){
var t = this;
this.dateElement = dateElement; this.timeElement = timeElement;
this.date = dateInstance instanceof Date ? dateInstance : new Date;
this.dateValue = function(dateInstance){
if(dateInstance instanceof Date)this.date = dateInstance;
var dt = this.date;
return dt.getFullYear()+'-'+(dt.getMonth()+1).toString().replace(/^(\d)$/, '0$1')+'-'+dt.getDate().toString().replace(/^(\d)$/, '0$1');
}
this.showDate = function(dateInstance){
this.dateElement.value = this.dateValue(dateInstance);
return this;
}
this.timeValue = function(dateInstance){
if(dateInstance instanceof Date)this.date = dateInstance;
var dt = this.date;
return dt.getHours().toString().replace(/^(\d)$/, '0$1')+':'+dt.getMinutes().toString().replace(/^(\d)$/, '0$1');
}
this.showTime = function(dateInstance){
this.timeElement.value = this.timeValue(dateInstance);
return this;
}
this.showDate().showTime();
this.dateChange = function(changeFunc, noTimeFunc){
this.dateElement.oninput = function(){
var v = this.value, s = t.timeElement.value;
if(v === '')v = this.value = t.dateValue(noTimeFunc(t));
if(s === '')s = t.timeValue(this.date);
t.date = new Date(v+' '+s); changeFunc(t.date, t);
}
return this;
}
this.timeChange = function(changeFunc, noTimeFunc){
this.timeElement.oninput = function(){
var v = this.value, s = t.dateElement.value;
if(v === '')v = this.value = t.timeValue(noTimeFunc(t));
if(s === '')s = t.dateValue(this.date);
t.date = new Date(s+' '+v); changeFunc(t.date, t);
}
return this;
}
}
var dateElement = I('date'), timeElement = I('time');
function threeHoursLater(){
return new Date(Date.now()+10800000);
}
var dt = new DateTime(dateElement, timeElement, threeHoursLater()); // 3 hours from now - initial date time set
function consoleIt(dateInstance){
console.log('display of dt.date --> '+dateInstance.toString());
console.log('dt.date for server --> '+dateInstance.getTime());
}
consoleIt(dt.date);
dt.dateChange(function(r){
consoleIt(r);
}, threeHoursLater).timeChange(function(a){
consoleIt(a);
}, threeHoursLater);
}); // end load
//]]>
<input id='date' type='date' />
<input id='time' type='time' />
Close those inputs and see what happens! Oh, make sure you validate those dates on your Server. The Client can be altered.
I have update the above code to include a DateTime constructor. The arguments should be clear.
PS
I noticed that there is an issue in Firefox 67.0 (64-bit) with change events, on Elements that do not receive focus first, therefore .onchange was changed to .oninput, which seems to work across the board.

Try to add default date for it
document.getElementById("creation-from-date").value = setDefautValue();
function setDefautValue() {
var date = new Date(); // today
date.setUTCHours(0, 0, 0, 0); //set default time 00:00 AM
const dStr = date.toISOString()
// remove seconds and milliseconds
return dStr.substring(0, dStr.indexOf(':', dStr.indexOf(':')+1))
}

You can try using Javascripts date:
$("creation-from-date").val(new Date().toLocalString());
// toLocalString() will return the local time while toISOString() will return the UTC time.
Here a good jQuery extension that is pretty useful for initializing datetime and datetime-local inputs:
// To initialize, simply call the method:
$('input[type="datetime-local"]').setNow();
Hope this helps.

Related

Changing a ISO date to a Short date JavaScript

I currently have a function setup to get the following two weeks or months from the selected date from a input date field. However, the problem I'm facing is that I want to get the date to output DD/MM/YYYY but I'm getting the full ISO date where I need the short. Does anyone know how I can go about doing this?
EDIT:
I've added the moment(date1).format('DD/MM/YYYY'); to test the code but this hasn't provided any results.
function submit() {
var type = document.getElementById("selectType").value;
var dateSelected = document.getElementById('datePicker').valueAsDate = new Date();
if (type === "Months") {
document.getElementById("pWeeks").className = "hidden";
document.getElementById("pMonths").className = "";
var date1 = dateSelected;
moment(date1).format('DD/MM/YYYY');
var date2 = new Date(date1);
date2.setMonth(date2.getMonth() + 1);
document.getElementById("pM1").innerHTML = date1;
document.getElementById("pM2").innerHTML = date2;
} else {
document.getElementById("pWeeks").className = "";
document.getElementById("pMonths").className = "hidden";
var date1 = dateSelected;
var date2 = new Date(date1);
date2.setDate(date2.getDate() + 7);
document.getElementById("pW1").innerHTML = date1;
document.getElementById("pW2").innerHTML = date2;
}
}
.hidden {
display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
<input type="date" id="datePicker"><br>
<select id="selectType">
<option value="Months">Months</option>
<option value="Weeks">Weeks</option>
</select><br>
<button id="submit" onclick="submit()">Submit</button>
<div id="pMonths" class="">
<p id="pM1"></p>
<p id="pM2"></p>
</div>
<div id="pWeeks" class="">
<p id="pW1"></p>
<p id="pW2"></p>
</div>
First off, you are setting the input value to the current date right here
var dateSelected = document.getElementById('datePicker').valueAsDate = new Date();
don't do that, it kind of defeats the purpose of having a selector in the first place.
As for converting the Dates, I would use Date.prototype.toLocaleDateString() passing "en-US" as the locale:
console.log((new Date()).toLocaleDateString('en-US')); // format MM/DD/YYY
I also fixed how you set the new dates, it now takes one date and adds either one and two months or one and to weeks instead of none and one month and none and one week ;-)
function submit() {
var type = document.getElementById("selectType").value;
var dateSelected = document.getElementById('datePicker').valueAsDate;
if (type === "Months") {
document.getElementById("pWeeks").className = "hidden";
document.getElementById("pMonths").className = "";
var date1 = dateSelected;
var datePlusOne = new Date(date1);
datePlusOne.setMonth(date1.getMonth() + 1);
var datePlusTwo = new Date(date1);
datePlusTwo.setMonth(date1.getMonth() + 2);
document.getElementById("pM1").innerHTML = datePlusOne.toLocaleDateString('en-US');
document.getElementById("pM2").innerHTML = datePlusTwo.toLocaleDateString('en-US');
} else {
document.getElementById("pWeeks").className = "";
document.getElementById("pMonths").className = "hidden";
var date1 = dateSelected;
var datePlusOne = new Date(date1);
datePlusOne.setDate(date1.getDate() + 7);
var datePlusTwo = new Date(date1);
datePlusTwo.setDate(date1.getDate() + 14);
document.getElementById("pW1").innerHTML = datePlusOne.toLocaleDateString('en-US');
document.getElementById("pW2").innerHTML = datePlusTwo.toLocaleDateString('en-US');
}
}
.hidden {
display: none;
}
<input type="date" id="datePicker"><br>
<select id="selectType">
<option value="Months">Months</option>
<option value="Weeks">Weeks</option>
</select><br>
<button id="submit" onclick="submit()">Submit</button>
<div id="pMonths" class="">
<p id="pM1"></p>
<p id="pM2"></p>
</div>
<div id="pWeeks" class="">
<p id="pW1"></p>
<p id="pW2"></p>
</div>
Instead of document.getElementById("pM1").innerHTML = date1; you should build first a string with the methods provided by the date object ( getFullYear, getDate, getMonth; see docu ). Then you can assign the string to the innerHtml.
If you can use the moment.js then your code which you assign to your innerHtml is date1 = moment(dateSelected).format('DD/MM/YYYY')
Also I would recommend Luca's way:
As for converting the Dates, I would use Date.prototype.toLocaleDateString() passing "en-US"
which would look at your code:
dateSelected.toLocaleDateString('en-US')
You could use MomentJS library to keep things simple:
Include the library :
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.14.1/moment.min.js"></script>
document.getElementById("pM1").innerHTML = moment(date1).format('DD/MM/YYYY');
document.getElementById("pM2").innerHTML = moment(date2).format('DD/MM/YYYY');
and in the else:
document.getElementById("pW1").innerHTML = moment(date1).format('DD/MM/YYYY');
document.getElementById("pW2").innerHTML = moment(date2).add(1, 'week').format('DD/MM/YYYY');

multiple alarm clock in javascript using dynamic generated input elements in javascript

I am trying to make a web page which will allow to set multiple alarms using dynamic element creation property of javascript but I'm not able to get the values of these multiple elements and create a alert on that time.
This is my code so far
<div id="TextBoxContainer">
<!--Textboxes will be added here -->
</div>
<br />
<input id="btnAdd" type="button" value="add" onclick="AddTextBox();" />
<script type="text/javascript">
var room = 0;
var i = 0;
function GetDynamicTextBox(){
return '<div>Alarm ' + room +':</div><input type="number"style="text-align:center;margin:auto;padding:0px;width:200px;" min="0" max="23" placeholder="hour" id="a'+room+'" /><input type="number" min="0" max="59" placeholder="minute" style="text-align:center; padding:0px; margin:auto; width:200px;" id="b'+room+'" /><input type="date" style="margin:auto;text-align:center; width:200px; padding:10px"><input type="button" value ="Set" onclick = "AddAlarm('+room+');" /> <input type="button" value ="Remove" onclick = "RemoveTextBox(this)" />';
}
function AddTextBox() {
var div = document.createElement('DIV');
div.innerHTML = GetDynamicTextBox("");
document.getElementById("TextBoxContainer").appendChild(div);
}
function RemoveTextBox(div) {
document.getElementById("TextBoxContainer").removeChild(div.parentNode);
}
function RecreateDynamicTextboxes() {
var html = "";
html += "<div>" + GetDynamicTextBox() + "</div>";
document.getElementById("TextBoxContainer").innerHTML = html;
room++;
}
window.onload = RecreateDynamicTextboxes;
function AddAlarm(values){
var hour = document.getElementById('');
var minute = document.getElementById('');
var date = document.getElementById('');
}
</script>
To create a notification whenever a given time or state is reached, I think you are looking for setInterval (see reference).
This method allows you to take action at a regular interval and it tries to honor that interval the best it can. It opens to a common mistake if your action can take longer than that interval duration so be careful not using a too short interval. In such case, actions can overlap and weird behavior will occur. You do not want that to happen so don't be too greedy when using that.
For an alarm project, I would recommend an interval of one second.
Example (not tested):
JavaScript
var alarmDate = new Date();
alarmDate.setHours(7);
alarmDate.setMinutes(15);
// set day, month, year, etc.
var ONE_SECOND = 1000; // miliseconds
var alarmClock = setInterval(function() {
var currentDate = new Date();
if (currentDate.getHours() == alarmDate.getHours() &&
currentDate.getMinutes() == alarmDate.getMinutes()
/* compare other fields at your convenience */ ) {
alert('Alarm triggered at ' + currentDate);
// better use something better than alert for that?
}, ONE_SECOND);
To add dynamic alarms, you could put them into an array then have your setInterval iterate over it.
In the long run you will probably get sick of alert and feel the need to use something that doesn't break the flow of your application. There are a lot of possibilities, one being the use of lightboxes that could stack over each other. That way you would be able to miss an alarm and still be notified by the next one.
Hope this helps and good luck!
You forgot the ID attribute on the date input and you were collecting the input elements in AddAlarm instead of their values.
EDIT: To check the alarms you have to store them and check every minute, if the current date matches one of the alarms. I added a short implementation there.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="TextBoxContainer">
<!--Textboxes will be added here -->
</div>
<br />
<input id="btnAdd" type="button" value="add" onclick="AddTextBox();" />
<script type="text/javascript">
var alarms = {};
var room = 0;
var i = 0;
setInterval(function() {
var current = new Date();
for (var nr in alarms) {
var alarm = alarms[nr];
console.log("checking alarm " + nr + " (" + alarm + ")");
if(current.getHours() == alarm.getHours()
&& current.getMinutes() == alarm.getMinutes()) { // also check for day, month and year
alert("ALERT\n"+alarm);
} else{
console.log('Alarm ' + nr + '('+alarm+') not matching current date ' + current);
}
}
}, 60000);
function GetDynamicTextBox(){
return '<div>Alarm ' + room +':</div><input type="number"style="text-align:center;margin:auto;padding:0px;width:200px;" min="0" max="23" placeholder="hour" id="a'+room+'" /><input type="number" min="0" max="59" placeholder="minute" style="text-align:center; padding:0px; margin:auto; width:200px;" id="b'+room+'" /><input type="date" style="margin:auto;text-align:center; width:200px; padding:10px" id="c'+room+'"><input type="button" value ="Set" onclick = "AddAlarm('+room+');" /> <input type="button" value ="Remove" onclick = "RemoveTextBox(this)" />';
}
function AddTextBox() {
var div = document.createElement('DIV');
div.innerHTML = GetDynamicTextBox("");
document.getElementById("TextBoxContainer").appendChild(div);
}
function RemoveTextBox(div) {
document.getElementById("TextBoxContainer").removeChild(div.parentNode);
}
function RecreateDynamicTextboxes() {
var html = "";
html += "<div>" + GetDynamicTextBox() + "</div>";
document.getElementById("TextBoxContainer").innerHTML = html;
room++;
}
window.onload = RecreateDynamicTextboxes;
function AddAlarm(values){
var hour = $('#a'+values).val();
var minute = $('#b'+values).val();
var date = $('#c'+values).val();
console.log(hour + ':' + minute + ' on ' + date);
var dateObj = new Date(date);
dateObj.setMinutes(minute);
dateObj.setHours(hour);
console.log(dateObj);
alarms[values] = dateObj;
}
</script>
So far I'm able to generate a alert when the values match the system time but I don't know how to delete the array value when an element is deleted. I am not able to do it. This is my code so far:
<script type="text/javascript">
var snd = new Audio("clock.mp3"); // buffers automatically when created
// Get
if (localStorage.getItem("test")) {
data = JSON.parse(localStorage.getItem("test"));
} else {
// No data, start with an empty array
data = [];
}
var today = new Date();
var d = today.getDay();
var h = today.getHours();
var m = today.getMinutes();
//since page reloads then we will just check it first for the data
function check() {
//current system values
console.log("inside check");
//if time found in the array the create a alert and delete that array object
for(var i = 0; i < data.length; i++) {
var today = new Date();
var d = today.getDay();
var h = today.getHours();
var m = today.getMinutes();
if (data[i].hours == h && data[i].minutes == m && data[i].dates == d ) {
data.splice(i,1);
localStorage["test"] = JSON.stringify(data);
snd.play();
alert("Wake Up Man ! Alarm is over ");
}
}
if((data.length)>0)
{
setTimeout(check, 1000);
}
}
//we do not want to run the loop everytime so we will use day to check
for(var i =0 ; i< data.length; i++)
{
if((data[i].dates == d) && (data[i].hours >= h) && (data[i].minutes >= m) )
{
check();
}
}
console.log(data);
var room = 1;
//var data = [];
var i = 0;
function GetDynamicTextBox(){
var date = new Date();
var h = date.getHours();
var m = date.getMinutes();
var d = date.getDay();
return '<div>Alarm ' + room +':</div><input type="number" style="text-align:center;margin:auto;padding:0px;width:200px;" min="0" max="23" value ='+h+' placeholder="hour" id="a'+room+'" /> <input type="number" min="0" max="59" placeholder="minute" style="text-align:center; padding:0px; margin:auto; width:200px;" id="b'+room+'" value ='+m+' /> <select id="c'+room+'" style="margin:auto; width:150px; padding:10px; color: black" required> <option value="1">Monday</option> <option value="2">Tuesday</option> <option value="3">Wednesday</option> <option value="4">Thursday</option> <option value="5">Friday</option> <option value="6">Saturday</option> <option value="0">Sunday</option> </select> <input type="button" value ="Set" onclick = "AddAlarm('+room+');" /> <input type="button" value ="Remove" onclick = "RemoveTextBox(this)" />';
}
function AddTextBox() {
room++;
var div = document.createElement('DIV');
div.innerHTML = GetDynamicTextBox("");
document.getElementById("TextBoxContainer").appendChild(div);
}
function RemoveTextBox(div) {
document.getElementById("TextBoxContainer").removeChild(div.parentNode);
}
function RecreateDynamicTextboxes() {
var html = "";
html += "<div>" + GetDynamicTextBox() + "</div>";
document.getElementById("TextBoxContainer").innerHTML = html;
}
window.onload = RecreateDynamicTextboxes;
function AddAlarm(values){
var hour = $('#a'+values).val();
var minute = $('#b'+values).val();
var date = $('#c'+values).val();
//get the current time and date
var today = new Date();
//current system values
var d = today.getDay();
var h = today.getHours();
var m = today.getMinutes();
//first check that whether a same date present in the array or not then push it
var found = -1;
for(var i = 0; i < data.length; i++) {
if (data[i].hours == hour && data[i].minutes == minute && data[i].dates == date ) {
found = 0;
break;
}
}
//if value does not present then push it into the array
if(found == -1)
{
data.push({hours: hour, minutes: minute, dates: date});
//storing it into localstorage
localStorage.setItem("test", JSON.stringify(data));
}
else
{
alert("Same value Exists");
}
//console.log(data);
function check() {
//current system values
//console.log("inside check");
//if time found in the array the create a alert and delete that array object
for(var i = 0; i < data.length; i++) {
var today = new Date();
var d = today.getDay();
var h = today.getHours();
var m = today.getMinutes();
if (data[i].hours == h && data[i].minutes == m && data[i].dates == d ) {
data.splice(i,1);
snd.play();
alert("Wake Up Man ! Alarm is over ");
}
}
if((data.length)>0)
{
setTimeout(check, 1000);
}
}
//we do not want to run the loop everytime so we will use day to check
for(var i =0 ; i< data.length; i++)
{
if((data[i].dates == d) && (data[i].hours >= h) && (data[i].minutes >= m))
{
check();
}
}
}
</script>

How I can interpret the correct date in Javascript when the year is of the format yy?

I have defined an input that accepts only dates in HTML.
The user can enter the date manually or by using a Calendar which is defined in javascript.
I am using Javascript and Jquery to convert the input to a date:
var lStartDateText = $j("#DateStarte").val();
var lEndDateText = $j("#DateEnd").val();
var lEffStartDate = new Date(lStartDateText);
var lEffEndDate = new Date(lEndDateText);
My problem is that when the user enters the following date manually 1/1/50 is interpreted as 1/1/1950 but 1/1/49 is interpreted as 1/1/2049. I want it always to be interpreted as 20xx.
On the other hand the Calendar allows the user to choose a year from 2006 to 2021 in case the user wants to choose a date from it and not enter it manually.
Hope I can get some help here ??
Try this
var lStartDateText = $j("#DateStarte").val();
var lEndDateText = $j("#DateEnd").val();
var lEffStartDate = ReFormatDate(lStartDateText);
var lEffEndDate = ReFormatDate(lEndDateText);
function ReFormatDate(dateString) {
var dateParts = dateString.split("/");
if (dateParts[2].length === 2) {
dateParts[2] = "20" + dateParts[2];
}
return new Date(dateParts.join("/"));
}
use this
var lStartDateText = "1/1/50" ;
var lEndDateText = "1/1/49" ;
var res = lStartDateText.slice(4);
var starttext = lStartDateText.replace(res,"20"+res);
var res1 = lEndDateText.slice(4);
var endtext = lEndDateText.replace(res1,"20"+res1);
alert(starttext);
alert(endtext);
var lEffStartDate = new Date(starttext);
alert("start date"+lEffStartDate);
var lEffEndDate = new Date(endtext);
alert("End Date"+lEffEndDate);
If you know your getting the last 2 digits of the year (50), and you know you always want to add the first 2 digits, which are constant (20), that's a slight modification to your code:
var lStartDateText = '20' + $j("#DateStarte").val();
var lEndDateText = '20' + $j("#DateEnd").val();
Note that this is not particularly robust, e.g. if the user enters text which is not a date you might end up with a string like '20hi', but that may be outside the scope of your question and it will be parsed as an invalid date.
$('#year').on('change keyup', function() {
var y = $('#year').val();
if (y.length === 2) {
y = '20' + y
}
if (y.length === 4) {
var dateY = new Date();
dateY.setFullYear(y);
$('#result').html(dateY);
} else {
$('#result').html('No YY or YYYY date found');
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<label for="year">Enter year (YY or YYYY)</label>
<input id="year" type="text">
<div id="result"></div>
i hope it's will be help you.
$('#year').on('change keyup', function() {
var right_date = $('#year').val();
var data = $('#year').val().split('/');
if (data[2].length == 2){
var twoDigitsCurrentYear = parseInt(new Date().getFullYear().toString().substr(0,2));
$('#result').html(data[0]+'/'+data[1]+'/'+twoDigitsCurrentYear + data[2]);
}
else {
$('#result').html(right_date);
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<label for="year">Enter year (YY or YYYY)</label>
<input id="year" type="text" placeholder="dd/mm/yy">
<div id="result"></div>

Get events in full calendar given dates from DTP on button click. Jquery/Javascript

<p> From: </p>
<input type="date" id="from-date" class="form-control"/>
<p> To: </p>
<input type="date" id="to-date" class="form-control"/>
<p> From: </p>
<input type="date" id="from-date-copy" class="form-control"/>
<p> To: </p>
<input type="date" id="to-date-copy" class="form-control"/>
<input type="button" id="copy">
Hi guys, I have this first 2 date time pickers to set the span of dates to get in the FullCalendar, and the other set of 2 date time pickers where to copy the events.
Example I have..
1/13/2016 as start date
and
1/15/2016 as end date << DATE / EVENTS TO COPY
AND 1/20/2016 and 1/22/2016 <-- WHERE TO COPY
I will get all events from 1/13/2016 and 1/15/2016 and transfer the events to 1/20/2016 and 1/22/2016. Please help.
First picture:
Second picture:
I used this code :
function bindCopyEventsButton() {
$("#copy").click(function(event) {
var eventsInDay;
var eventsHolder = [];
var startDate = $("#from-date").val();
var endDate = new Date($("#to-date").val());
var whereToCopyStartDate = new Date($('#from-date-copy').val());
var whereToCopyEndDate = new Date($('#to-date-copy').val());
var whereToCopyStart = whereToCopyStartDate.getDate();
var whereToCopyEnd = whereToCopyEndDate.getDate();
var e1start = new Date(startDate);
var e1end = endDate == null ? e1start : endDate;
for (var d = e1start; d <= e1end; d.setDate(d.getDate() + 1)) {
//Get all events in the day
eventsInDay = getEventsInDay(d);
//For copy and paste. Will be used later. It's currently performing cut and paste
//eventsHolder.push(eventsInDay);
//Iterate all events in the day for updating
for(var e = 0; e < eventsInDay.length; e++) {
//Check if still applicable
if(whereToCopyStart <= whereToCopyEnd){
//Get start hour of the event
var startTimeHour = eventsInDay[e].start._i.getHours();
console.log("startTimeHour : " + startTimeHour);
//Get end hour of the event
var endTimeHour = eventsInDay[e].end._i.getHours();
console.log("endTimeHour : " + endTimeHour);
//Get start date of the event
var x = eventsInDay[e].start._i.getDate();
console.log("Start date.getDate : " + x);
//Get end date of the event
var y = eventsInDay[e].end._i.getDate();
console.log("End date.getDate : " + y);
//Set start date of the event to the value of the from date
eventsInDay[e].start._i.setDate(whereToCopyStart);
//If the start date and end date are the same use same end date. else start date + 1
if(x == y){
eventsInDay[e].end._i.setDate(whereToCopyStart);
} else {
eventsInDay[e].end._i.setDate(whereToCopyStart + 1);
}
console.log("Event GET START DATE : " + eventsInDay[e].start._i.getDate());
console.log("Event GET END DATE : " + eventsInDay[e].end._i.getDate());
//Set the start hours of event
eventsInDay[e].start._i.setHours(startTimeHour);
//Set the end hours of event
eventsInDay[e].end._i.setHours(endTimeHour);
//Update Calendar
$('#preferred-schedule').fullCalendar('updateEvent', eventsInDay[e]);
//Add 1 to the **where to copy** start date
whereToCopyStart = (whereToCopyStart + 1);
}
}
}
});
}
function getEventsInDay(date) {
return $('#preferred-schedule').fullCalendar('clientEvents', function(evt) {
if (date >= evt.start && date <= evt.end) {
return true;
}
});
}
I think I'm getting the right info. but again. The clientEvents doesn't get the events in the day. and the updateEvent doesn't reflect on the FullCalendar. But when I'm debugging I think I'm getting the right infos based on the logs.
The value comparisons are not completely correct (you will need to do some date manipulations), but I think this is kind of what you're looking for, using the clientEvents and updateEvent methods of FullCalendar:
//Find all the events that match the criteria
var events = $('#calendar').fullCalendar('clientEvents', function(evt){
if(evt.start >= $('#from-date').val() && evt.end <= $('#to-date').val()){
return true;
}
return false;
});
//Loop through the events and update them
for(var e = 0; e < events.length; e++){
events[e].start = $('#from-date-copy');
events[e].end = $('#to-date-copy');
$('#calendar').fullCalendar('updateEvent', events[e]);
}
Hopefully this gives you a push in the right direction.
Maybe Helpful Hint
To see how the clientEvents function works and what format it
returns data in, you can use the fullCalendar demo
(http://fullcalendar.io/js/fullcalendar-2.6.0/demos/agenda-views.html).
Open Chrome DevTools and use this function: var events =
$('#calendar').fullCalendar('clientEvents', function(evt){return
true;}); then print out events.

How to compare date with current date for applying logic

<script>
$(document).ready(function(){
if(date.now()>($("[id$=clear2]").val)+2){
$("[id$=clear]").val("");
$("[id$=clear2]").val("");// date value
$("[id$=clear3]").val("");
}
});
</script>
I want to check that current date(dd/mm/yyyy) is greater than date(dd/mm/yyyy) value + 2 days .I was working several scenarios .that by removing if condition it is working fine .By using this it is not working well .Can you show some solution so that i can move forward
Try this:
var d1 = '31/11/2015'.split('/');
var d2 = '27/12/2015'.split('/');
var date1 = new Date(d1[2],d1[1],d1[0]); // YYYY,MM,DD
var date2 = new Date(d2[2],d2[1],d2[0]);
var numOfDaysToAdd = 2;
date2.setDate(date2.getDate() + numOfDaysToAdd);
if (date1.getTime() < date2.getTime()) {
alert('date1 is before date2');
}
Working with dates in javascrip:
javascript
$(document).ready(function () {
var today = new Date();
var tomorrow = new Date(today);
tomorrow.setDate(today.getDate() + 1);
$("#today").val(today.toUTCString());
$("#tomorrow").val(tomorrow.toUTCString());
$("#checkDate").click(function () {
var newDate = new Date($("#today").val());
newDate.setDate(newDate.getDate() + 2);
var parsedTomorrow = new Date($("#tomorrow").val());
var comRes = newDate > parsedTomorrow;
alert(comRes);
});
});
HTML
<input type="text" id="today" />
<input type="text" id="tomorrow" />
<input type="button" id="checkDate" />
DEMO
Use JavaScript Date Object to compare dates in javascript.

Categories

Resources