Check if month pass in datetimepicker - javascript

I have an calculator that calculates the hourdiff between two datetime values.
I want when selected month ends and new month start the calculation starts from the beginning.
Now all goes ok for Feb month but when somebody want start calc from March then it calculates for 28 days and not for 31
My Code:
<script>
$(function () {
$('#frompicker').datetimepicker({ dateFormat: 'd/M/yy' });
$('#topicker').datetimepicker({ dateFormat: 'd/M/yy' });
});
<script>
$(document).ready(function () {
function calculateTime() {
//get values
var valuestart = $("#frompicker").val();
var valuestop = $("#topicker").val();
//alert(valuestart);
var timeStart = new Date(valuestart);
var timeEnd = new Date(valuestop);
var hourDiff = (timeEnd - timeStart) / 3600000;
if (hourDiff < 0) {
$("p").html("<b>price:</b> " + "wrong data" );
else if (hourDiff > 24&& hourDiff <= 672) { //28days
$("p").html("<b>price:</b> " + "100.00" + "€");
}
else if (hourDiff >= 672) { //
var hourDiffnew = hourDiff - 672;
var finalpricep61 = (hourDiffnew * 0.125) + 90;
var finalpricep62 = finalpricep61.toFixed();
$("p").html("<b>price:</b> " + finalpricep62 + ".00€");
}

Given:
var valuestart = $("#frompicker").val();
what is valuestart? A string or timevalue? If it's a string, then likely the following will not work as expected in some browsers:
var timeStart = new Date(valuestart);
var timeEnd = new Date(valuestop);
Assuming these Date objects have appropriate values, and that:
when selected month ends and new month start the calculation starts from the beginning
means start from the beginning of the month, then:
if (timeStart.getMonth() != timeEnd.getMonth()) {
timeStart.setDate(1);
timeStart.setMonth(timeEnd.getMonth());
}
will set timeStart to the first of the same month as timeEnd. But I might have misinterpreted the question.

Related

Convert javascript from single date exclusion to multiple dates

With our limited knowledge we were able to exclude certain dates in a date delivery module based on weekday and time. See code below.
But now we want to exclude all Wednesdays and Saturdays in the next year if you select carrier 99. So multiple disabledDays.push(excldatum) being each Wednesday and Saturday for one year starting from today if this particular carrier is selected.
Can someone please help us how to write that code?
var selected_carrier = parseInt($('.delivery_option_radio:checked').val());
var weekdag = new Date().getDay();
var uur = new Date().getHours();
var vandaag = new Date();
var morgen = new Date();
morgen.setDate(vandaag.getDate() + 1);
var exclmaand = morgen.getMonth() + 1;
var excldag = morgen.getDate();
var excldatum = exclmaand + "-" + excldag;
// carrier is postnl
if (selected_carrier == 99) {
// weekdag 0 is zondag t/m 6 is zaterdag
if (weekdag > -1 && weekdag < 5) {
// na 23 uur
if (uur >= 23) {
disabledDays.push(excldatum);
}
}
}
if (selected_carrier == 99) {
// weekdag 5 is vrijdag
if (weekdag == 5) {
// na 10 uur
if (uur >= 10) {
disabledDays.push(excldatum);
}
}
}
Something like the following piece of code might work for you. It gets all dates for the specified weekdaysToProcess for the next 365 days starting today. Eg. [3,6] for Wednesday and Saturday.
You can add any other filtering you like of course.
function GetDatesForWeekdaysForNext365Days(weekdaysToProcess) {
var currentDate = new Date();
var foundDates = [];
for (var day = 0; day < 365; day++) {
var calculatedDate = new Date();
calculatedDate.setDate(currentDate.getDate() + day);
var calculatedWeekDay = calculatedDate.getDay();
if (weekdaysToProcess.includes(calculatedWeekDay)) {
foundDates.push(calculatedDate);
}
}
return foundDates;
}
The function can be called for carrier 99 like:
disabledDays = GetDatesForWeekdaysForNext365Days([3,6]);

Iterating through timeslots

I'm having a little difficulty with the logic here, it's getting late and honestly, I'm stumped.
I need to loop through time slots.
var settings = {
startOfWeek:0, //0 = Sunday, 1 = Monday
timeSlotGap: 30,
minTime: "09:00:00",
maxTime: "17:30:00",
numSlots: 0
};
So I can specify a time slot gap, so if I was to iterate through the time slots (with a 30 minute gap) it would be:
09:00
09:30
10:00
10:30
Currently I have the following:
$(document).ready(function () {
getNumSlots(settings.minTime, settings.maxTime, settings.timeSlotGap);
for(var i = 1; i<=settings.numSlots; i++){
//I have no idea what I'm doing here
$('#calendar').append("<p>Timeslot:" + i +"</p>");
}
});
var WeekNo = moment().week();
var CurrentDate = getCurrentDate();
var WeekDay = moment().weekday();
var settings = {
startOfWeek:0, //0 = Sunday, 1 = Monday
timeSlotGap: 60,
minTime: "09:00:00",
maxTime: "17:30:00",
numSlots: 0
};
if(settings.startOfWeek == 0){
WeekDay = WeekDay - 1;
}
function getNumSlots(minTime, maxTime, timeSlotGap){
var minTimeSplit = minTime.split(":");
var hourStart = new Date("01/01/1900 " + minTime).getHours();
var hourEnd = new Date("01/01/1900 " + maxTime).getHours();
var minStart = new Date("01/01/1900 " + minTime).getMinutes();
var minEnd = new Date("01/01/1900 " + maxTime).getMinutes();
var diffHour = hourEnd - hourStart;
var diffMins = minEnd - minStart;
var slots = ((diffHour * 60) + diffMins) / timeSlotGap;
settings.numSlots = slots;
}
If it was as simple as looping through 30/60 minutes that wouldn't be a problem but since I can specify anything for the time slot i.e. 90 minutes it makes it a tad difficult.
To get the time slots you could use something like the following:
var settings = {
startOfWeek:0, //0 = Sunday, 1 = Monday
timeSlotGap: 30,
minTime: "09:00:00",
maxTime: "17:30:00",
numSlots: 0
};
function getTimeDate(time) {
var timeParts = time.split(':');
var d = new Date();
d.setHours(timeParts[0]);
d.setMinutes(timeParts[1]);
d.setSeconds(timeParts[2]);
return d;
}
function getTimeSlots(startDate, endDate, interval) {
var slots = [];
var intervalMillis = interval * 60 * 1000;
while (startDate < endDate) {
// So that you get "00" if we're on the hour.
var mins = (startDate.getMinutes() + '0').slice(0, 2);
slots.push(startDate.getHours() + ':' + mins);
startDate.setTime(startDate.getTime() + intervalMillis);
}
return slots;
}
var slots = getTimeSlots(
getTimeDate(settings.minTime), getTimeDate(settings.maxTime), settings.timeSlotGap
);
Here's an example JSFiddle.

Javascript / jQuery two datepickers calculate date range

I use the Javascript below to calculate days out of a date range (2 Zebra Datepickers) and to pass the value to input field 'nights' .. then process a form.
While my Javascript works fine, i fail to achieve the same result with jQuery .val()
Javascript:
setDifference = function(form)
{
var x = document.getElementById('startDate').value;
var y = document.getElementById('endDate').value;
var arr1 = x.split('-');
var arr2 = y.split('-');
var dt1 = new Date();
dt1.setFullYear(arr1[2], arr1[1], arr1[0]);
var dt2 = new Date();
dt2.setFullYear(arr2[2], arr2[1], arr2[0]);
document.getElementById('nights').value = (dt2.valueOf() - dt1.valueOf()) / (60 * 60 * 24 * 1000)
}
jQuery i tried so far:
$(function() {
var startDate = $('#startDate').val();
var endDate = $('#endDate').val();
var dateSplit = startDate.split("-");
var dateSplit = endDate.split("-");
dateDiff = new Date(dateSplit[1] + " " + dateSplit[0] + ", " + dateSplit[2]);
var dateDiff = new Date(endDate - startDate);
var days = dateDiff/1000/60/60/24;
$('#nights').val(days);
});
Error i get is either 'NaN or 'invalid date' on all browsers i tried.
You have declared dateSplit two times. hence startdate and enddate would be same.

javascript date validation - checking two dates

i have two input box for getting date value in the format "dd/mm/yyyy".
i have to create coupon for a shop, so i have to check 1st date should be from tomorrow.
for ex. if today is 5th sep, then 1st date should not be before 6th sep.
and 2nd date should be atleast 1day greater than the 1st date. if user entered 1st date as 10th sep, then 2nd date should not be same or before 10th sep.
so if a user enters 31st jan 2013 ( 31/01/2013) as 1st date then 2nd date can be 1st feb or any date after 1st feb. so i hvae to check the date validation also.
for date validation i am using the following code -
function chkdate(y,m,d)
{
var date = new Date(y,m-1,d);
month1 = date.getMonth()+1;
date1 =date.getDate();
if(month1 <10)
{
month1 = "0"+month1;
}
if(date1 <10)
{
date1 = "0"+date1;
}
var convertedDate =""+date.getFullYear() + (month1) + date1;
var givenDate = "" + y + m + d;
return ((givenDate==convertedDate)?true:false);
}
i am callling above function inside a function -
function generate_coupon()
{
var f_arr = from_date.split("/"); //from_date is from 1st input date value.
var f_day = f_arr[0];
var f_month =f_arr[1];
var f_year =f_arr[2];
var t_arr = to_date.split("/"); //to_date is from 2nd input date value.
var t_day = t_arr[0];
var t_month =t_arr[1];
var t_year =t_arr[2];
if (chkdate(f_year,f_month,f_day)== true && chkdate(t_year,t_month,t_day)== true)
{
}
else
{
alert('Enter Valid Date - dd/mm/yyyy');
}
}
in that if condition i have to check both date values - the 1st date value is from tomorrow or not and 2nd date value should differ from 1st date by atleast 1 day. if both conditions are true then i wil generate a coupon or else i will alert invalid date.
how should i do it ??
rather doing this type of validation, i think it will be more easy for you that you fill the other date field you self using some defined code. and made those fields UN-editable
Farid has made a good point, however if your base date is dynamic something like this should work:
function isValidInput(date1, date2) {
return date2 >= getNextDate(date1);
}
function getNextDate(date) {
// The number of milliseconds in one day
var ONE_DAY = 1000 * 60 * 60 * 24;
var date_ms = date.getTime();
var nextDate_ms = date_ms + ONE_DAY;
var nextDate = new Date(nextDate_ms);
// Make sure to get rid of time, so that it's always at 00:00:00 hour.
return new Date(nextDate.getYear(), nextDate.getMonth(), nextDate.getYear());
}
function checkDates(d1, d2) {
if (d1 instanceof Date && d2 instanceof Date) {
var today = new Date();
today.setHours(0, 0, 0, 0);
if (date1.getTime() < (today.getTime() + 86400000)) {
return "First date should be after today";
}
if (date2.getTime() < (date1.getTime() + 86400000)) {
return "Second date should be after First date";
}
return "Dates are valid";
}
return "One or more invalid date";
}
var date1Str = "6/9/2012";
var date2Str = "7/9/2012";
var date1Arr = date1Str.split("/");
var date2Arr = date2Str.split("/");
var date1 = new Date(date1Arr[2], date1Arr[1] - 1, date1Arr[0]);
var date2 = new Date(date2Arr[2], date2Arr[1] - 1, date2Arr[0]);
alert(checkDates(date1, date2));
Try this
function generate_coupon() {
var from_date = document.getElementById("fromDate");
var to_date = document.getElementById("toDate");
var from = new Date(from_date.value);
var to = new Date(to_date.value);
var today = new Date();
var tomorrow = new Date(new Date().getTime() + 24 * 60 * 60 * 1000);
if (from >= tomorrow && to > from) {
} else {
alert('Enter Valid Date - dd/mm/yyyy');
}
}​

Javascript: wrong date calculation

So I just have posted a question about this code (which was answered):
$(document).ready(Main);
function Main() {
ConfigDate();
}
function ConfigDate() {
var currentTime = new Date();
var dayofWeek = currentTime.getDay();
var daysSinceThursday = (dayofWeek + 3) % 7
var lastThursday = new Date(currentTime.getDate() - daysSinceThursday);
var dd = lastThursday.getDate();
var mm = lastThursday.getMonth() + 1;
var yyyy = lastThursday.getFullYear();
$("#last_thursday").text(yyyy + " / " + mm + " / " + dd);
}
The problem now is that the date that appears in my cell is 1969 / 12 / 31 (which isn't even a thursday).
Did I do something wrong while calculating last thursday date?
This is because .getDate() returns the day of the month. So you are building your date based on a serial number of something less than 30, which won't even set your seconds above 1.
Use .setDate() instead of building a new date:
date.setDate(date.getDate() - daysSinceThursday);
.setDate() will modify your existing date object, it doesn't return a new date.
You're trying to set a Date based only on the day of the month of the last Thursday. Try something like this:
var daysSinceThursday = (dayofWeek + 3) % 7;
var lastThursday = new Date(currentTime.getTime());
lastThursday.setDate(currentTime.getDate() - daysSinceThursday);
var dd = lastThursday.getDate();
var mm = lastThursday.getMonth() + 1;
var yyyy = lastThursday.getFullYear();
http://jsfiddle.net/rAuRF/3/

Categories

Resources