Count days between two dates excluding weekends - db2
How can I find the difference between two dates in DB2 (excluding weekends)?
Are there any functions that will do this in DB2? Or do I need to write a query myself?
There is AFAIK no such function. It is however easy to write a query that calculates this:
with cal(d) as (
values date('2015-01-01') -- start_date
union all
select d + 1 day from cal
where d < '2015-01-15' -- end_date
) select count(case when dayofweek(d) between 2 and 6 then 1 end)
from cal;
If you do a lot of these kind of calculations you might want to create a calendar table, you can add attributes like national holiday etc to this table.
you can use this function:
DAYOFWEEK(CURRENT_DATE)
The following calculation will return the number of working days between two dates:
[Week(End Date) - Week(Start Date)] * 5 + [DayofWeek(Start Date) - DayofWeek(End Date)]
This will only work if the functions for Week and Day or equivalent are native to the database driver. Client Access and Sybase native connection both support these functions.
The Week function will give the integer value of the week of the year selected. The DayofWeek will give an Integer value from 1-7 for the day selected.
IBM Support Working Days Between Two Dates
This is the best way to implement difference between two dates excluding weekend means Saturday and Sunday and also excluding national holiday....
/******
* First, we'll extend the date object with some functionality.
* We'll add an .each() function, as well as an .adjust() function.
* .each() will give us the ability to loop between two dates, whether
* by 'day', 'week' or 'month'.
* .adjust() will allow us to move a given day by a given unit. This is used
* like so: currentDate.adjust('days', 1) to increment by one day.
******/
Date.prototype.each = function(endDate, part, step, fn, bind){
var fromDate = new Date(this.getTime()),
toDate = new Date(endDate.getTime()),
pm = fromDate <= toDate? 1:-1,
i = 0;
while( (pm === 1 && fromDate <= toDate) || (pm === -1 && fromDate >= toDate) ){
if(fn.call(bind, fromDate, i, this) === false) break;
i += step;
fromDate.adjust(part, step*pm);
}
return this;
};
Date.prototype.adjust = function(part, amount){
part = part.toLowerCase();
var map = {
years: 'FullYear', months: 'Month', weeks: 'Hours', days: 'Hours', hours: 'Hours',
minutes: 'Minutes', seconds: 'Seconds', milliseconds: 'Milliseconds',
utcyears: 'UTCFullYear', utcmonths: 'UTCMonth', weeks: 'UTCHours', utcdays: 'UTCHours',
utchours: 'UTCHours', utcminutes: 'UTCMinutes', utcseconds: 'UTCSeconds', utcmilliseconds: 'UTCMilliseconds'
},
mapPart = map[part];
if(part == 'weeks' || part == 'utcweeks')
amount *= 168;
if(part == 'days' || part == 'utcdays')
amount *= 24;
this['set'+ mapPart]( this['get'+ mapPart]() + amount );
return this;
}
/*******
* An array of national holidays. This is used to test for the exclusion of given
* days. While this list is national days, you could tailor it to regional, state
* or given religious observances. Whatever.
******/
natDays = [
{
month: 1,
date: 26,
type: "national - us",
name: "New Year's Day"
},
{
month: 1,
date: 21,
type: "national - us",
name: "Martin Luther King Day"
},
{
month: 2,
date: 18,
type: "national - us",
name: "President's Day (Washington's Birthday"
},
{
month: 5,
date: 27,
type: "national - us",
name: "Memorial Day"
},
{
month: 7,
date: 4,
type: "national - us",
name: "Independence Day"
},
{
month: 9,
date: 2,
type: "national - us",
name: "Labor Day"
},
{
month: 10,
date: 14,
type: "national - us",
name: "Columbus Day"
},
{
month: 11,
date: 11,
type: "national - us",
name: "Veteran's Day"
},
{
month: 11,
date: 29,
type: "national - us",
name: "Thanksgiving Day"
},
{
month: 12,
date: 25,
type: "national - us",
name: "Christmas Day"
}
];
/******
* This uses the national holidays array we just set, and checks a given day to see
* if it's in the list. If so, it returns true and the name of the holiday, if not
* it returns false.
*****/
function nationalDay(date) {
for (i = 0; i < natDays.length; i++) {
if (date.getMonth() == (natDays[i].month-1)
&& date.getDate() == natDays[i].date) {
return [true, natDays[i].name];
}
}
return [false, null];
}
/******
* This function takes two dates, as start and end date, and iterates through the
* dates between them. For each date, it checks if the current date is a week day.
* If it is, it then checks if it isn't a holiday. In this case, it increments
* the business day counter.
******/
function calcBusinessDays(startDate, endDate) {
// input given as Date objects
var iDateDiff=0, holidays = [];
startDate.each(endDate, 'days', 1, function(currentDate, currentStep, thisDate){
if(currentDate.getDay() != 0 && currentDate.getDay() != 6 ) {
var isAHoliday = nationalDay(currentDate);
if(!isAHoliday[0]){
iDateDiff += 1;
} else {
holidays.push(isAHoliday[1]);
}
}
});
return {count: iDateDiff, holidays: holidays};
};
$(function(){
var results, exclusions;
$( "#startDate" ).datepicker({
defaultDate: "+1w",
changeMonth: true,
numberOfMonths: 3,
onClose: function( selectedDate ) {
$( "#endDate" ).datepicker( "option", "minDate", selectedDate );
}
});
$( "#endDate" ).datepicker({
defaultDate: "+1w",
changeMonth: true,
numberOfMonths: 3,
onClose: function( selectedDate ) {
$( "#startDate" ).datepicker( "option", "maxDate", selectedDate );
}
});
$("#calculateMe").on("click", function(){
var startDate = new Date($("#startDate").val()),
endDate = new Date($("#endDate").val() );
// Calculate the number of business days. This returns an object, with
// two members: count and holidays
results = calcBusinessDays(startDate, endDate);
exclusions = "Excluded weekends";
if (results.holidays.length > 0) {
// We have holidays, tell the user about them...
exclusions += " and the following holidays: ";
for(var i=0; i<results.holidays.length; i += 1){
exclusions += results.holidays[i]+", ";
}
} else {
// No holidays.
exclusions += ".";
}
$("#result").text(results.count + " business days." ).append("<p>("+exclusions+")</p>");
});
});
<div id="content">
<input type="text" class="myDateClass" id="startDate"/>
<input type="text" class="myDateClass" id="endDate"/>
<button id="calculateMe">How many business days?</button>
<div id="result"></div>
</div>
Fiddle
Related
How I to find and add any input field in the synch fusion calendar code?
var generateEvents = function () { var eventData = []; var eventSubjects = [ 'Bering Sea Gold', 'Technology', 'Maintenance', 'Meeting', 'Travelling', 'Annual Conference', 'Birthday Celebration', 'Farewell Celebration', 'Wedding Anniversary', 'Alaska: The Last Frontier', 'Deadliest Catch', 'Sports Day', 'MoonShiners', 'Close Encounters', 'HighWay Thru Hell', 'Daily Planet', 'Cash Cab', 'Basketball Practice', 'Rugby Match', 'Guitar Class', 'Music Lessons', 'Doctor checkup', 'Brazil - Mexico', 'Opening ceremony', 'Final presentation' ]; var weekDate = new Date(new Date().setDate(new Date().getDate() - new Date().getDay())); var startDate = new Date(weekDate.getFullYear(), weekDate.getMonth(), weekDate.getDate(), 10, 0); var endDate = new Date(weekDate.getFullYear(), weekDate.getMonth(), weekDate.getDate(), 11, 30); eventData.push({ Id: 1, Subject: eventSubjects[Math.floor(Math.random() * (24 - 0 + 1) + 0)], StartTime: startDate, EndTime: endDate, Location: '', Description: 'Event Scheduled', RecurrenceRule: 'FREQ=WEEKLY;BYDAY=MO,TU,WE,TH,FR;INTERVAL=1;COUNT=10;', IsAllDay: false, IsReadonly: false, CalendarId: 1 }); I have tried inspecting the code and tried to add the input field eventData, but not working. I want to add the Input field of my choice and want to send the input field data to the firestore database.
Enable Particular Date in datepicker
I have disabled all Mondays in datepicker but on some dates I have to enable that particular date on Monday, so how can I do that? I have pasted the code : const datepicker2 = new Datepicker(elem2, { daysOfWeekDisabled: dates_diable, beforeShowDay: function(date) { dmy = date.getDate() + "-" + (date.getMonth()+1) + "-" + date.getFullYear(); console.log(dmy+' : '+($.inArray(dmy, availableDates))); if ($.inArray(dmy, availableDates) > '-1') { //console.log('yes'); return true; } }, format: 'dd/mm/yyyy', buttonClass: 'btn', minDate:"Today", maxDate:maxDate, datesDisabled: [], todayHighlight: false, });
How to Match Start Date and End Date [duplicate]
How to get start ( 00:00:00 ) and end ( 23:59:59 ) of today in timestamp ( GMT )? Computer use a local time.
var start = new Date(); start.setUTCHours(0,0,0,0); var end = new Date(); end.setUTCHours(23,59,59,999); alert( start.toUTCString() + ':' + end.toUTCString() ); If you need to get the UTC time from those, you can use UTC().
With dayjs library, use startOf and endOf methods as follows: Local GMT: const start = dayjs().startOf('day'); // set to 12:00 am today const end = dayjs().endOf('day'); // set to 23:59 pm today For UTC: const utc = require('dayjs/plugin/utc'); dayjs.extend(utc); const start = dayjs.utc().startOf('day'); const end = dayjs.utc().endOf('day'); Using the (deprecated) momentjs library, this can be achieved with the startOf() and endOf() methods on the moment's current date object, passing the string 'day' as arguments: Local GMT: var start = moment().startOf('day'); // set to 12:00 am today var end = moment().endOf('day'); // set to 23:59 pm today For UTC: var start = moment.utc().startOf('day'); var end = moment.utc().endOf('day');
Using the luxon.js library, same can be achieved using startOf and endOf methods by passing the 'day' as parameter var DateTime = luxon.DateTime; DateTime.local().startOf('day').toUTC().toISO(); //2017-11-16T18:30:00.000Z DateTime.local().endOf('day').toUTC().toISO(); //2017-11-17T18:29:59.999Z DateTime.fromISO(new Date().toISOString()).startOf('day').toUTC().toISO(); //2017-11-16T18:30:00.000Z remove .toUTC() if you need only the local time and you may ask why not moment.js, answer is here for that.
FYI (merged version of Tvanfosson) it will return actual date => date when you are calling function export const today = { iso: { start: () => new Date(new Date().setHours(0, 0, 0, 0)).toISOString(), now: () => new Date().toISOString(), end: () => new Date(new Date().setHours(23, 59, 59, 999)).toISOString() }, local: { start: () => new Date(new Date(new Date().setHours(0, 0, 0, 0)).toString().split('GMT')[0] + ' UTC').toISOString(), now: () => new Date(new Date().toString().split('GMT')[0] + ' UTC').toISOString(), end: () => new Date(new Date(new Date().setHours(23, 59, 59, 999)).toString().split('GMT')[0] + ' UTC').toISOString() } } // how to use today.local.now(); //"2018-09-07T01:48:48.000Z" BAKU +04:00 today.iso.now(); // "2018-09-06T21:49:00.304Z" * * it is applicable for Instant time type on Java8 which convert your local time automatically depending on your region.(if you are planning write global app)
In MomentJs We can declare it like : const start = moment().format('YYYY-MM-DD 00:00:01'); const end = moment().format('YYYY-MM-DD 23:59:59');
One liner - considering local timezone and without libraries const todayStart = new Date(new Date().setHours(0, 0, 0, 0)) const todayEnd = new Date(new Date().setHours(23, 59, 59, 999)) const tomorrowStart = new Date(new Date(new Date().setHours(0, 0, 0, 0)).setDate(new Date().getDate() + 1)) const tomorrowEnd = new Date(new Date(new Date().setHours(23, 59, 59, 999)).setDate(new Date().getDate() + 1)) const monthStart = new Date(new Date(new Date().getFullYear(), new Date().getMonth(), 1).setHours(0, 0, 0, 0)) const monthEnd = new Date(new Date(new Date().getFullYear(), new Date().getMonth() + 1, 0).setHours(23, 59, 59, 999)) const nextMonthStart = new Date(new Date(new Date().getFullYear(), new Date().getMonth() + 1, 1).setHours(0, 0, 0, 0)) const nextMonthEnd = new Date(new Date(new Date().getFullYear(), new Date().getMonth() + 2, 0).setHours(23, 59, 59, 999)) console.log({ todayStart, todayEnd, tomorrowStart, tomorrowEnd, monthStart, monthEnd, nextMonthStart, nextMonthEnd, })
If you're just interested in timestamps in GMT you can also do this, which can be conveniently adapted for different intervals (hour: 1000 * 60 * 60, 12 hours: 1000 * 60 * 60 * 12, etc.) const interval = 1000 * 60 * 60 * 24; // 24 hours in milliseconds let startOfDay = Math.floor(Date.now() / interval) * interval; let endOfDay = startOfDay + interval - 1; // 23:59:59:9999
I prefer to use date-fns library for date manipulating. It is really great modular and consistent tool. You can get start and end of the day this way: var startOfDay = dateFns.startOfDay; var endOfDay = dateFns.endOfDay; console.log('start of day ==> ', startOfDay(new Date('2015-11-11'))); console.log('end of day ==> ', endOfDay(new Date('2015-11-11'))); <script src="https://cdnjs.cloudflare.com/ajax/libs/date-fns/1.29.0/date_fns.min.js"></script>
We can use moment for this. // for day start time moment(moment().startOf('day')).format('HH:mm') // for day end time moment(moment().endOf('day')).format('HH:mm')
As you are interested in the UTC start/end of day, you can also use the modulo operator: const now = new Date().getTime(); let startOfDay = now - (now % 86400000); let endDate = startOfDay + 86400000; where 86400 is the number of seconds of one day and the resulting variables are the Epoch in milliseconds. If you prefer Date Objects: const now = new Date().getTime(); let startOfDay = new Date(now - (now % 86400000)); let endDate = new Date(now - (now % 86400000) + 86400000);
Based on the most rated answer, but to define the dates in just one line: const startToday = new Date(new Date().setUTCHours(0,0,0,0)); const endToday = new Date(new Date().setUTCHours(23,59,59,999)); Explanation: new Date().setUTCHours(0,0,0,0) // returns the epoch time number new Date(/* epoch number */) // returns that epoch Date object that is why both new Date constructors are needed.
It might be a little tricky, but you can make use of Intl.DateTimeFormat. The snippet bellow can help you convert any date with any timezone to its begining/end time. const beginingOfDay = (options = {}) => { const { date = new Date(), timeZone } = options; const parts = Intl.DateTimeFormat("en-US", { timeZone, hourCycle: "h23", hour: "numeric", minute: "numeric", second: "numeric", }).formatToParts(date); const hour = parseInt(parts.find((i) => i.type === "hour").value); const minute = parseInt(parts.find((i) => i.type === "minute").value); const second = parseInt(parts.find((i) => i.type === "second").value); return new Date( 1000 * Math.floor( (date - hour * 3600000 - minute * 60000 - second * 1000) / 1000 ) ); }; const endOfDay = (...args) => new Date(beginingOfDay(...args).getTime() + 86399999); const beginingOfYear = () => {}; console.log(beginingOfDay({ timeZone: "GMT" })); console.log(endOfDay({ timeZone: "GMT" })); console.log(beginingOfDay({ timeZone: "Asia/Tokyo" })); console.log(endOfDay({ timeZone: "Asia/Tokyo" }));
// get current time for UTC timezone const d = new Date(); const year = d.getUTCFullYear(); const month = d.getUTCMonth(); const day = d.getUTCDate(); // set time to begin day UTC const startTime = Date.UTC(year, month, day, 0, 0, 0, 0); //set time to end day UTC const endTime = Date.UTC(year, month, day, 23, 59, 0, 0);
Datatable Date format is not working correctly
My date is showing in datatable in this format : "2013-09-02 12:00:00 AM". I want it in this format: "2013/09/02". I've googled and found a way to do so. But the code is not working. Output is showing "NaN/NaN/NaN". My script for datatable is here: $(document).ready(function () { $('#RequisitionTbl').dataTable({ "aoColumnDefs": [ { "aTargets": [0], "sType": 'date', "fnRender": function (oObj) { // trying to format(like "2013/09/02") the date here var javascriptDate = new Date(oObj.aData[0]); javascriptDate = javascriptDate.getDate() + "/" + javascriptDate.getMonth() + "/" + javascriptDate.getFullYear(); return "<div class= date>" + javascriptDate + "<div>"; } }, { "sWidth": "350px", "aTargets": [0] }, { "sWidth": "180px", "aTargets": [1] }, { "sWidth": "200px", "aTargets": [2] }, { "bSortable": false, "aTargets": [4] }, { "bSearchable": false, "aTargets": [4] } ], "sDom": "<'row-fluid'<'span6'l><'span6'f>r>t<'row-fluid'<'span6'i><'span6'p>>", "sPaginationType": "bootstrap", "oLanguage": { "sLengthMenu": "Display _MENU_ records" } }).columnFilter({ sPlaceHolder: "head:before", aoColumns: [ { type: 'date-range' }, ,{},] }); }); Need help to fin out the problem.
Remember that Month is zero-based index: var currentDate = new Date(); var day = currentDate.getDate(); var month = currentDate.getMonth() + 1; var year = currentDate.getFullYear(); var javascriptDate = year + '/' + month + '/' + day // Modify as you need Hope this helps!
DHTMLX Recurring Events in MVC3
I was using DHTMLX Scheduler in my MVC3 project. I need to use Recurring events scheduler. All the configurations seems fine except DB. I need to know what are the necessary fields i need to include on the server for recurring events. And How about the xml configuration and data retrieval for the recurring events. In that sample tutorial consist of server end code as in php. So i can't come to know how to write code for MVC environment. Pls guide me how can i do this. Index function init() { scheduler.templates.event_text = function (start, end, ev) { return 'Event: ' + ev.Description + ''; }; scheduler.templates.calendar_month = scheduler.date.date_to_str("%F %Y"); scheduler.config.full_day = true; scheduler.locale.labels.full_day = "Full day"; //week label of calendar scheduler.templates.calendar_scale_date = scheduler.date.date_to_str("%D"); //date value on the event's details form scheduler.templates.calendar_time = scheduler.date.date_to_str("%d-%m-%Y"); scheduler.config.repeat_date = "%m-%d-%Y"; scheduler.config.update_render = "true"; scheduler.locale.labels.section_category = 'Category'; scheduler.locale.labels.section_location = 'Title'; scheduler.config.lightbox.sections = [ { name: "location", height: 15, map_to: "title", type: "textarea" }, { name: "description", height: 50, map_to: "text", type: "textarea", focus: true }, { name: "recurring", height: 115, type: "recurring", map_to: "rec_type", button: "recurring" }, { name: "time", height: 72, type: "time", map_to: "auto" }, { name: "category", height: 22, type: "select", map_to: "category", options: [ {key:"", label:"Select Category"}, {key:"A", label:"Public"}, {key:"P", label:"Private"}, {key:"C", label:"Closed"} ]} ] scheduler.config.xml_date = "%m/%d/%Y %H:%i"; scheduler.init("scheduler_here", new Date(), "month"); scheduler.load("/Admin/EventCalendar/Dat"); var dp = new dataProcessor("/Admin/EventCalendar/Save"); dp.init(scheduler); dp.setTransactionMode("POST", false); } Thanks.
You need to define 4 field for related record in DB rec_type, will be week_1___6 ( each week, on Sunday ) start_date - first date of occurence end_date - last date of occurence ( set it to year 9999 if event has not end date ) event_length - length of events in seconds, will be 36600 in you case