I have set up a page that holds 2 pickadates. One for a start date and one for an end date.
I also have a number of checkboxes, labeled:
1 Day, 1 Month, 1 Year
Once the user selects a date from the first pickadate. They can either pick a second date from the second pickadate.
But I wish to offer a second alternative. Where if they check 1 day, the 2nd pickadate will be the result of 1 day + the 1st pickdate. Likewise for the 1 month and 1 year checkbox.
Is there anyway to accomplish this?
My current HTML is:
<div class="inputdata">
<label>Timeframe:</label>
<span>
<div class="section__block section__block--scoped">
From:
<fieldset>
<input type="text" id="input_from">
</fieldset>
To:
<fieldset>
<input type="text" id="input_to">
</fieldset>
</div>
</span>
<div class="clear"></div>
<span><input id="x_timeframe" type="date" name="date_timeframe"></span>
<label></label>
<span id="x_timeframe_checkboxes">
<input type="radio" name="a_timeframe" id="radio4" value="d" class="css-checkbox"/>
<label for="radio4" class="css-label">1 Day</label>
<input type="radio" name="a_timeframe" id="radio5" value="w" class="css-checkbox" />
<label for="radio5" class="css-label">1 Week</label>
<input type="radio" name="a_timeframe" id="radio6" value="m" class="css-checkbox" />
<label for="radio6" class="css-label">1 Month</label>
<input type="radio" name="a_timeframe" id="radio8" value="n" class="css-checkbox" />
<label for="radio8" class="css-label">None</label>
</span>
</div>
Just for familiarity, the js includes:
<script src="/x/js/calendar/pickadate.js-3.4.0/lib/picker.js"></script>
<script src="/x/js/calendar/pickadate.js-3.4.0/lib/picker.date.js"></script>
<script src="/x/js/calendar/pickadate.js-3.4.0/lib/picker.time.js"></script>
<script src="/x/js/calendar/pickadate.js-3.4.0/lib/legacy.js"></script>
<script src="/x/js/calendar/pickadate.js-3.4.0/demo/scripts/main.js"></script>
<script src="/x/js/calendar/pickadate.js-3.4.0/lib/pickadate1454.js"></script>
+1 Day on #from_picker
var from_picker = $('#input_from').pickadate(), to_picker = $('#input_from').pickadate();
from_picker.pickadate('picker').on('set', function (event) {
if (event.select) {
to_picker.pickadate('picker').set('select', from_picker.pickadate('picker').get('select').pick + 1 * 24 * 60 * 60 * 1000);
}
});
You could use only JS to do the trick, by getting the value from you date field and transform in a js Date and the add the Days or Moths.
I always create 7 functions, to work with date in JS: addSeconds, addMinutes, addHours, addDays, addWeeks, addMonths, addYears.
You can see an example here: http://jsfiddle.net/tiagoajacobi/YHA8x/
How to use:
var now = new Date();
console.log(now.addWeeks(3));
This are the functions:
Date.prototype.addSeconds = function(seconds) {
this.setSeconds(this.getSeconds() + seconds);
return this;
};
Date.prototype.addMinutes = function(minutes) {
this.setMinutes(this.getMinutes() + minutes);
return this;
};
Date.prototype.addHours = function(hours) {
this.setHours(this.getHours() + hours);
return this;
};
Date.prototype.addDays = function(days) {
this.setDate(this.getDate() + days);
return this;
};
Date.prototype.addWeeks = function(weeks) {
this.addDays(weeks*7);
return this;
};
Date.prototype.addMonths = function (months) {
var dt = this.getDate();
this.setMonth(this.getMonth() + months);
var currDt = this.getDate();
if (dt !== currDt) {
this.addDays(-currDt);
}
return this;
};
Date.prototype.addYears = function(years) {
var dt = this.getDate();
this.setFullYear(this.getFullYear() + years);
var currDt = this.getDate();
if (dt !== currDt) {
this.addDays(-currDt);
}
return this;
};
Related
I am trying to make an alarm with JS, it works fine but in order for it to work I need to put "17" for hours instead of "5 PM" which makes more sense. Take a look at the code here:
JS:
function soundAlarm() {
var mer = document.getElementById('meridian').value;
var h = document.getElementById('hourSelector').value;
var m = document.getElementById('minuteSelector').value;
alert("Successfully scheduled alarm!");
setInterval(function(){
var date = new Date();
var hours = date.getHours();
var minutes = date.getMinutes();
if (mer == "1"){
hours = hours;
}
if (mer == "2"){
hours = hours + 12;
}
if (h == hours && m == minutes){
document.getElementById('ringtone').play();
}
});}
HTML:
<audio id="ringtone" src="SamsungS6Mp3Ringtones.mp3" autostart="false" repeat="true"></audio>
<div class="page">
<span id="setAlarmTime"><u>Set Alarm Time</u></span>
<br><br>
<input type="number" id="hourSelector" placeholder="Hours...">
<input type="number" id="minuteSelector" placeholder="Minutes...">
<select id="meridian">
<option value="1"> AM </option>
<option value="2"> PM </option>
</select>
<br><br>
<button onclick = "soundAlarm();" id="set"> Set </button>
</div>
Hi I'm very novice at Javascript so apologies for asking naff questions.
This piece of code is returning a Nan when it should retrieve days elapsed.
Is the second function causing the issue?
Here it is:
<body>
<script>
function elapsedTime(date1, date2) {
var start = new Date(date1);
var startMilli = start.getTime();
var end = new Date(date2);
var endMilli = end.getTime();
var elapsed = (endMilli - startMilli);
alert(millisToDaysHoursMinutes(elapsed));
}
function millisToDaysHoursMinutes(millis) {
var seconds = millis / 1000;
var totalMinutes = seconds / 60;
var minutesPerDay = 60 * 24;
var days = totalMinutes / minutesPerDay;
return days;
}
</script>
<form>
Start:<input type="text" name="date1" value="dd/m/year" /><br>
End: <input type="text" name="date2" value="dd/m/year" />
<input type="button" name="button1" onclick="elapsedTime(date1.value, date2.value)" value="Get Elapsed Time" />
</form>
</body>
You need to ensure that the dates entered are valid else you'll get a NaN (Not a Number). Use input type=date and make them required then you can easily check that they're valid before calling your date diff function.
EG:
function elapsedTime(date1, date2) {
var start = new Date(date1);
var startMilli = start.getTime();
var end = new Date(date2);
var endMilli = end.getTime();
var elapsed = (endMilli - startMilli);
alert(millisToDaysHoursMinutes(elapsed));
}
function millisToDaysHoursMinutes(millis) {
var seconds = millis / 1000;
var totalMinutes = seconds / 60;
var minutesPerDay = 60 * 24;
var days = totalMinutes / minutesPerDay;
return days;
}
var date1 = document.querySelector("input[name=date1]"),
date2 = document.querySelector("input[name=date2]"),
button1 = document.querySelector("input[name=button1]");
button1.addEventListener("click", function() {
var date1valid = date1.checkValidity();
var date2valid = date2.checkValidity();
if (date1valid && date2valid) {
elapsedTime(date1.value, date2.value);
} else {
alert("Please provide both dates!");
}
});
<form>
Start:<input type="date" name="date1" required="required" value="dd/m/year" /><br> End: <input type="date" name="date2" required="required" value="dd/m/year" />
<input type="button" name="button1" value="Get Elapsed Time" />
</form>
You should use input type date to make your code work:
<form>
Start:<input type="date" name="date1" /><br>
End: <input type="date" name="date2" />
<input type="button" name="button1" onclick="elapsedTime(date1.value, date2.value)" value="Get Elapsed Time" />
</form>
I have a form with a date and time field, the date field consists of 3 fields: day, month and year. And time field consists of 2 fields, hour and minute.
I want to show an alert if the date is older than 2 months and 60 hours.
HTML:
<div class="container-date">
<div class="date_day">
<input type="text" maxlength="2" name="input_day" id="input_day" value="">
</div>
<div class="date_month">
<input type="text" maxlength="2" name="input_month" id="input_month" value="">
</div>
<div class="date_year>
<input type="text" maxlength="4" name="input_year" id="input_year" value="">
</div>
</div>
<div class="container-time">
<div class="time_hour>
<input type="text" maxlength="2" name="input_hour" id="input_hour" value="">
</div>
<div class="time_minute">
<input type="text" maxlength="2" name="input_minute" id="input_minute" value="">
</div>
</div>
I can do it with one field only for date, but have now 3 fields that I need.
I tried something like this:
jQuery(document).ready(function($){
var day = $('#input_day');
var month = $('#input_month');
var year = $('#input_year');
var today = new Date();
var currentMonth = today.getMonth();
month.on("input change", function() {
if ((today.getMonth() + 11) - (this + 11) > 4) {
console.log('test');
}
});
});
I'd suggest you to parse the form date, create the comparison date according to the expected period and then return if the formDate is greater than comparisonDate.
Please, let me know if the code below is according to what you expected:
function getFormDate() {
const formYear = $("#input_year").val();
const formMonth = $("#input_month").val() - 1;
const formDay = $("#input_day").val();
const formHour = $("#input_hour").val();
const formMinute = $("#input_minute").val();
return new Date(formYear, formMonth, formDay, formHour, formMinute, 0, 0)
}
function getComparisonDate() {
const today = new Date()
let comparisonDate = new Date()
comparisonDate.setMonth(today.getMonth() - 2)
comparisonDate.setHours(today.getHours() - 60)
return comparisonDate
}
function thereIsMissingValue() {
let anyMissing = false;
const inputs = $(".container-date input, .container-time input")
inputs.each(function () {
if (!$(this).val())
anyMissing = true
});
return anyMissing
}
function displayMessage() {
const formDate = getFormDate()
const comparisonDate = getComparisonDate()
$("#min-allowed-date").text(comparisonDate.toLocaleString())
const isOlderThanComparison = formDate < comparisonDate
$(".older-date").toggle(isOlderThanComparison)
const isInTheFuture = formDate > new Date()
$(".future-date").toggle(isInTheFuture)
const isValidDate = !isOlderThanComparison && !isInTheFuture
$(".valid-date").toggle(isValidDate)
}
function calculate() {
if (thereIsMissingValue()) {
$(".container-date-validation").hide()
return
}
$(".container-date-validation").show()
displayMessage()
}
$('#input_year, #input_month, #input_day, #input_hour, #input_minute').change(function () { calculate(); })
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container-date">
<div class="date_day">
<label>Day</label>
<input type="text" maxlength="2" name="input_day" id="input_day" value="">
</div>
<div class="date_month">
<label>Month</label>
<input type="text" maxlength="2" name="input_month" id="input_month" value="">
</div>
<div class="date_year">
<label>Year</label>
<input type="text" maxlength="4" name="input_year" id="input_year" value="">
</div>
</div>
<div class="container-time">
<div class="time_hour">
<label>Hour</label>
<input type="text" maxlength="2" name="input_hour" id="input_hour" value="">
</div>
<div class="time_minute">
<label>Minute</label>
<input type="text" maxlength="2" name="input_minute" id="input_minute" value="">
</div>
</div>
<div class="container-date-validation" style="display:none">
<p class="older-date" style="display:none">Invalid date. Only dates after
<span id="min-allowed-date"></span> are allowed.
</p>
<p class="future-date" style="display:none">Invalid date. It doesn't allow dates in the future.</p>
<p class="valid-date">This is a valid date</p>
</div>
If you go with milliseconds :
2 months is 5184000000
60 hours is 216000000
total : 5400000000
the wantedDate will be new Date(year, month, day)
var wantedDate = new Date(year,month,day); // will create a date from the inputs
wantedDate.getTime() // will convert to miliseconds
and if you convert the wanted date to milliseconds you can easily find out
wantedDate < Date.now() && wantedDate > (Date.now() - 5400000000)
I really like using Moment.js for things like this. It uses much more human-readable code, like so:
const moment = require('moment'); // assumes you install Moment as a node module
const month = $('#input_month');
const day = $('#input_day');
const year = $('#input_year');
const hour = $('#input_hour');
const minute = $('#input_minute');
const checkDate = () => {
const inputDate = moment(month.val() + '/' + day.val() + '/' + year.val() + ' ' + hour.val() + ':' + minute.val(), "MM-DD-YYYY HH:mm");
const expDate = moment.subtract(2, "months").subtract(60, "hours");
if (moment(inputDate).isBefore(expDate, "minute") {
// do something
}
}
month.on('change', checkDate);
You'll also need to ensure you're getting usable values from your inputs. I suggest using number input types or select menus to restrict input options.
I have one dropdown and two textbox on my page. Now i have to bind the value
based on dropdown value.
My question is when i am select This Week from dropdown that time it will
display wrong date when first date of month on second textbox.
Look at the below example. It is working fine on other date of month but when
select '07/01/2017' then it's display like this '01/06/2017' rather then
'01/07/2017' on second textbox when we select This Week.
$(document).on("change","#selectDates",function() {
var dropValue = document.getElementById('selectDates').value;
//All
if (dropValue == "1") {
$('#txtDateFrom').val('');
$('#txtDateTo').val('');
}
//Today
else if (dropValue == "2") {
var back_GTM = new Date();
$('#txtDateFrom').val(Back_date(back_GTM));
$('#txtDateTo').val(Back_date(back_GTM));
}
//This Week
else if (dropValue == "3") {
//var curr = new Date; // get current date
var curr = new Date('07/01/2017'); // get current date
var first = curr.getDate() - curr.getDay(); // First day is the day of the month - the day of the week
var last = first + 6; // last day is the first day + 6
var firstday = new Date(curr.setDate(first));
var lastday = new Date(curr.setDate(last));
$('#txtDateFrom').val(Back_date(firstday));
$('#txtDateTo').val(Back_date(lastday));
}
});
function Back_date(back_GTM) {
var b_dd = back_GTM.getDate();
var b_mm = back_GTM.getMonth() + 1;
var b_yyyy = back_GTM.getFullYear();
if (b_dd < 10) {
b_dd = '0' + b_dd
}
if (b_mm < 10) {
b_mm = '0' + b_mm
}
return back_date = b_dd + '/' + b_mm + '/' + b_yyyy;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="select-style">
<select id="selectDates">
<option value="1" selected>All</option>
<option value="2">Today</option>
<option value="3">This Week</option>
</select>
</div>
<br /> <br />
<div class="input-group input-large" data-date="13/07/2013" data-date-format="dd/mm/yyyy">
<span class="input-group-addon">From</span>
<input type="text" id="txtDateFrom" class="form-control dpd1" name="from">
<span class="input-group-addon">To</span>
<input type="text" id="txtDateTo" class="form-control dpd2" name="to">
</div>
You should create two date objects for the cases where a week overlaps 2 months.
Because when you set the date to -5, from july 1st, 2017, it correctly calculates the date to sunday june 25th.
But now, the month has changed!
When you set the date to the last day of the week, which is 1, the month stays to june in the date object.
So having two different date objects to manipulate the dates separately is the fix.
$(document).on("change","#selectDates",function() {
var dropValue = document.getElementById('selectDates').value;
//All
if (dropValue == "1") {
$('#txtDateFrom').val('');
$('#txtDateTo').val('');
}
//Today
else if (dropValue == "2") {
var back_GTM = new Date();
$('#txtDateFrom').val(Back_date(back_GTM));
$('#txtDateTo').val(Back_date(back_GTM));
}
//This Week
else if (dropValue == "3") {
//var curr = new Date; // get current date
var curr = new Date('07/01/2017'); // get current date
var curr2 = new Date('07/01/2017'); // get current date - Second date object.
var first = curr.getDate() - curr.getDay(); // First day is the day of the month - the day of the week
var last = first + 6; // last day is the first day + 6
var firstday = new Date(curr.setDate(first));
var lastday = new Date(curr2.setDate(last));
$('#txtDateFrom').val(Back_date(firstday));
$('#txtDateTo').val(Back_date(lastday));
}
});
function Back_date(back_GTM) {
var b_dd = back_GTM.getDate();
var b_mm = back_GTM.getMonth() + 1;
var b_yyyy = back_GTM.getFullYear();
if (b_dd < 10) {
b_dd = '0' + b_dd
}
if (b_mm < 10) {
b_mm = '0' + b_mm
}
return back_date = b_dd + '/' + b_mm + '/' + b_yyyy;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="select-style">
<select id="selectDates">
<option value="1" selected>All</option>
<option value="2">Today</option>
<option value="3">This Week</option>
</select>
</div>
<br /> <br />
<div class="input-group input-large" data-date="13/07/2013" data-date-format="dd/mm/yyyy">
<span class="input-group-addon">From</span>
<input type="text" id="txtDateFrom" class="form-control dpd1" name="from">
<span class="input-group-addon">To</span>
<input type="text" id="txtDateTo" class="form-control dpd2" name="to">
</div>
For creating new date you should pass year, month index and date of month as prameters.
Example as follows:
var curr = new Date(2017,6,1);
Following needs to be fixed in your code:
// Needs to fix this
var curr = new Date('07/01/2017');
i have 2 time pickers in my page like
<div class="form-group">
<input class="time ui-timepicker-input" id="FromTime" name="FromTime" type="text" value="" autocomplete="off">
</div>
<div class="form-group">
<input class="time ui-timepicker-input" id="ToTime" name="FromTime" type="text" value="" autocomplete="off">
</div>
$(document).ready(function () {
$('#ToTime').timepicker();
$('#FromTime').timepicker();
});
Now i want to set ToTime = FromTime + 1 hour
To raise FromTime value change event and i use the code
$('#FromTime').timepicker().on('changeTime.timepicker', function(e) {
//how to get selected time here
//set ToTime value with a difference of 1 hour ie if 12:30 am selected set ToTime as 1:30 am
});
Try this code
Demo
JS
$(document).ready(function () {
$('#FromTime').timepicker({
defaultTime: false
});
});
var HoursToAdd = 2;
$('#FromTime').timepicker().on('changeTime.timepicker', function (e) {
var meridian = e.time.meridian
var hours = e.time.hours
var minutes = e.time.minutes
var seconds = e.time.seconds
var NewTime;
if (meridian == 'AM') {
NewTime = new Date('', '', '', hours, minutes, seconds)
} else if (meridian == 'PM') {
NewTime = new Date('', '', '', (hours + 12), minutes, seconds)
}
NewTime.setHours(NewTime.getHours() + HoursToAdd)
$('#ToTime').timepicker({
defaultTime: NewTime.getHours() + " : " + NewTime.getMinutes()
});
});