Set custom time on bootstrap TimePicker - javascript

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()
});
});

Related

Make the output of a span the value of an input

Good day all, i am building a form that uses javascript to get a client's local time which is correctly displayed in span element. However i wish to make the output of the span element the value of an input field in order to pass same into mysql. I tried php like below, it rather displays the code.
$currenttradetime = "<span id='digital-clock'></span>";
$currenttt = $currenttradetime;
?>
<input type='hidden' name="time" value="<?php echo $currenttt; ?>"></span>'>
Then using html/php, it equally displays the span html codes rather than the time. How do i achieve this?
function getDateTime() {
var now = new Date();
var year = now.getFullYear();
var month = now.getMonth()+1;
var day = now.getDate();
var hour = now.getHours();
var minute = now.getMinutes();
var second = now.getSeconds();
if(month.toString().length == 1) {
month = '0'+month;
}
if(day.toString().length == 1) {
day = '0'+day;
}
if(hour.toString().length == 1) {
hour = '0'+hour;
}
if(minute.toString().length == 1) {
minute = '0'+minute;
}
if(second.toString().length == 1) {
second = '0'+second;
}
var dateTime = hour+':'+minute+':'+second;
return dateTime;
}
// example usage: realtime clock
setInterval(function(){
currentTime = getDateTime();
document.getElementById("digital-clock").innerHTML = currentTime;
}, 1000);
The time is: <span id='digital-clock'></span>
<input type='text' value='<span id="digital-clock"></span>'>
Just use JavaScript to set the value of the input field like so:
function getDateTime() {
var now = new Date();
var year = now.getFullYear();
var month = now.getMonth()+1;
var day = now.getDate();
var hour = now.getHours();
var minute = now.getMinutes();
var second = now.getSeconds();
if(month.toString().length == 1) {
month = '0'+month;
}
if(day.toString().length == 1) {
day = '0'+day;
}
if(hour.toString().length == 1) {
hour = '0'+hour;
}
if(minute.toString().length == 1) {
minute = '0'+minute;
}
if(second.toString().length == 1) {
second = '0'+second;
}
var dateTime = hour+':'+minute+':'+second;
return dateTime;
}
// example usage: realtime clock
setInterval(function(){
currentTime = getDateTime();
document.getElementById("digital-clock").innerHTML = currentTime;
document.getElementById('time').value = currentTime;
}, 1000);
<span id="digital-clock"></span>
<input id="time" />
Change
<input type='hidden' name="time" value="<?php echo $currenttt; ?>"></span>'>
to have an id too and do not set the html as value for the input field:
<input id='digital-clock-inputfield' type='hidden' name="time" value=""></span>'>
then change
document.getElementById("digital-clock").innerHTML = currentTime;
to set the value of the input field too:
document.getElementById("digital-clock").innerHTML = currentTime;
document.getElementById("digital-clock-inputfield").value = currentTime;

Why do i have to put military time instead of just "Hour + meridian" in js alarm clock?

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>

Alert message if date and time is older than a value

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.

Date Filter Not Works on First Day of Month

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');

How to separate regex in javascript Hours format

I have some problem to define hours time, i want to separate hours time to 3 time type morning, evening, and night.
if time start from 00:00 to 10:00 the type time is morning,
if time start from 10:01 to 18:00 the type time is evening,
if time start from 18:01 to 23:59 the type time is night,
i have code jquery like this
$(document).ready(function(){
$('#submit').on('click',function(){
var hrs=$('#hours').val();
var nm=$('#scedule').val();
var patt = new RegExp("^([0-9]|0[0-9]|1[0-9]|2[0-3]):[0-5][0-9]$");
var patts = patt.test(hrs);
//morning = 00:00 - 10:00
var morn = new RegExp("^([0-9]|0[0-9]|1[0-9]):[0-5][0-9]$");
var morning = morn.test(hrs);
//evening = 10:01 - 18:00
var even = new RegExp("^(1[0-9]|[0-9]):[0-5][0-9]$");
var evening = even.test(hrs);
//night = 18:01 - 00:00
var nig = new RegExp("^(1[0-9]|2[0-3]):[0-5][0-9]$");
var night = nig.test(hrs);
if ( patts == morning ) {
alert('This is Morning');
} else if (patts == evening){
alert('This is Evening');
} else if (patts == night){
alert('This is night');
} else {
alert('Format is wrong');
}
});
});
and this is my form HTML :
Scedule : <input type="text" id="scedule"><br>
Time : <input type="text" id="hours"><br>
<input type="submit" value="submit" id="submit"><br>
You don't need a regex here, just use Date:
$(document).ready(function(){
$('#submit').on('click',function(){
var hrs=$('#hours').val();
if(hrs.length != 5 || hrs.indexOf(':') < 0)
{
alert("Wrong Fromat")
return;
}
var date = new Date();
date.setHours(hrs.split(":")[0]);
date.setMinutes(hrs.split(":")[1]);
console.log(date)
if ( date.getHours() < 10) {
console.log('This is Morning');
} else if (date.getHours() > 18 && date.getMinutes > 0){
console.log('This is night');
} else{
console.log('This is Evening');
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
Time : <input type="text" id="hours"><br>
<input type="submit" value="submit" id="submit"><br>

Categories

Resources