Java Datestring, how to create long Day of the Week format? - javascript

This is a script that counts a desired number of business days from the present time. It works very well. I would like it to render the result as a long word day of the week, as in Monday July 06 2015, for example. The current result is Mon Jul 06 2015
I am a hacking monkey, so a dumbed-down response would not be an insult!
Number.prototype.mod = function(n) {
return ((this % n) + n) % n;
}
Date.prototype.addBusDays = function(dd) {
var wks = Math.floor(dd / 5);
var dys = dd.mod(5);
var dy = this.getDay();
if (dy === 6 && dd > -1) {
if (dys === 0) {
dys -= 2;
dy += 2;
}
dys++;
dy -= 6;
}
if (dy === 0 && dd < 1) {
if (dys === 0) {
dys += 2;
dy -= 2;
}
dys--;
dy += 6;
}
if (dy + dys > 5) dys += 2;
if (dy + dys < 1) dys -= 2;
this.setDate(this.getDate() + wks * 7 + dys);
}
var today = new Date();
today.addBusDays(1);
document.getElementById('dtt').innerHTML = today.toDateString();
Usage: We use it in a full sentence:
Your package will arrive on or before <span id="dtt"></span>.

Just create an array of month/day names like so:
var days = ["Sunday","Monday",...];
var months = ["January", "February", ...];
And then
function formatDate(date) {
var day = date.getDate();
if(day < 10) {
day = "0" + day;
}
return days[date.getDay()] + " " + months[date.getMonth()] + " " + day + " " + date.getFullYear();
}
console.log(formatDate(new Date()));
http://jsfiddle.net/1xe39uut/2/

Related

Calculate the minutes between to dates excluding evenings and weekends?

I'm trying to calculate the business time between two dates, down to the minute. Business hours being defined as between 8 AM and 6 PM EST (or EDT if its daylight savings).
I've found this answer, which performs this in hours, but am unsure how to convert to minutes, and ensure my timezones wont be messed up:
https://stackoverflow.com/a/11092865/104998
function isHoliday( /*Date*/ date) {
for (var i = 0; i < holidays.length; i++) {
if (holidays[i].getTime() == date.getTime()) {
return true;
}
}
return false;
}
function diffHours( /*Date*/ d1, /*Date*/ d2) {
var date1 = new Date(d1.getUTCFullYear() + "-" + (d1.getUTCMonth() + 1) + "-" + d1.getUTCDate() + " UTC");
var date2 = new Date(d2.getUTCFullYear() + "-" + (d2.getUTCMonth() + 1) + "-" + d2.getUTCDate() + " UTC");
var sum = 0;
var oneday = 24 * 3600 * 1000;
var hours, date;
// first day
if (!isHoliday(date1)) {
// decrease by a whole day first (will be added later)
sum -= 10;
// add real hours
hours = d1.getUTCHours() + d1.getUTCMinutes() / 60;
if (hours <= 6) {
sum += 10 - hours;
} else if (hours <= 20) {
sum += 4;
} else {
sum += 24 - hours;
}
}
// last day
if (!isHoliday(date2)) {
// decrease by a whole day first (will be added later)
sum -= 10;
// add real hours
hours = d2.getUTCHours() + d2.getUTCMinutes() / 60;
if (hours <= 6) {
sum += hours;
} else if (hours <= 20) {
sum += 6;
} else {
sum += hours - 14;
}
}
// whole days
while (date1 <= date2) {
if (!isHoliday(date1)) {
sum += 10;
}
// increase date by 1 day
date1.setTime(date1.getTime() + oneday);
}
return Math.floor(sum);
}
// ==============
// examples below
// --------------
// array of Dates (in UTC) to skip
var holidays = [
new Date("2012-01-04 UTC"),
];
for (var i = 0; i < holidays.length; i++) {
console.log('holiday: ', holidays[i].toUTCString());
}
a = new Date("2012-01-01 12:00 UTC");
b = new Date("2012-01-02 12:00 UTC");
c = new Date("2012-01-02 22:00 UTC");
d = new Date("2012-01-03 07:00 UTC");
e = new Date("2012-01-05 12:00 UTC");
console.log({
d1: a.toUTCString(),
d2: b.toUTCString(),
hours: diffHours(a, b)
});
console.log({
d1: b.toUTCString(),
d2: c.toUTCString(),
hours: diffHours(b, c)
});
console.log({
d1: c.toUTCString(),
d2: d.toUTCString(),
hours: diffHours(c, d)
});
console.log({
d1: d.toUTCString(),
d2: e.toUTCString(),
hours: diffHours(d, e)
});
Any help would be much appreciated.
Here is the class I came up with to do this, there must be a better way (this is my first time delving into nodejs)
var dateFuncs = DateFuncs.prototype;
function DateFuncs() {
}
DateFuncs.prototype.isWeekend = function(pDate) {
return (pDate.getDay() == 0 || pDate.getDay() == 6);
}
DateFuncs.prototype.isBusinessMinute = function(pDate) {
var hours = pDate.getHours() + pDate.getMinutes()/60;
return (hours >= 8 && hours < 18); //business hours are 8AM-6PM
}
DateFuncs.prototype.addMinutes = function(date, minutes) {
return new Date(date.getTime() + minutes*60000);
}
DateFuncs.prototype.diffBusinessMins = function(/*Date*/ startDate, /*Date*/ endDate) {
var minutesDiff = 0;
startDate.setSeconds(0,0);
endDate.setSeconds(0,0);
var curDate = new Date(startDate.getTime());
while(curDate.getTime() != endDate.getTime())
{
if(!this.isWeekend(curDate) && this.isBusinessMinute(curDate))
{
minutesDiff += 1;
}
curDate = this.addMinutes(curDate, 1);
}
return minutesDiff;
}
module.exports = DateFuncs;

change date format function

I am trying to change a date format, would you please help me out to change the date format into this Mon, 12 Feb 2016 11:00?
Here is the code below:
function nicetime(a, out) {
var d = Math.round((+new Date - a) / 1000),
fuzzy = '',
n = 'mins',
d = d < 0 ? 0 : d;
if (out == 1) {
return d;
} else if (out == 0) {
var chunks = new Array();
chunks[0] = [60 * 60 * 24 * 365, 'year', 'years'];
chunks[1] = [60 * 60 * 24 * 30, 'month', 'months'];
chunks[2] = [60 * 60 * 24 * 7, 'week', 'weeks'];
chunks[3] = [60 * 60 * 24, 'day', 'days'];
chunks[4] = [60 * 60, 'hr', 'hrs'];
chunks[5] = [60, 'min', 'mins'];
var i = 0,
j = chunks.length;
for (i = 0; i < j; i++) {
s = chunks[i][0];
if ((xj = Math.floor(d / s)) != 0) {
n = xj == 1 ? chunks[i][1] : chunks[i][2];
break;
}
}
fuzzy += xj == 1 ? '1 ' + n : xj + ' ' + n;
if (i + 1 < j) {
s2 = chunks[i + 1][0];
if (((xj2 = Math.floor((d - (s * xj)) / s2)) != 0)) {
n2 = (xj2 == 1) ? chunks[i + 1][1] : chunks[i + 1][2];
fuzzy += (xj2 == 1) ? ' + 1 ' + n2 : ' + ' + xj2 + ' ' + n2;
}
}
fuzzy += ' ago';
return fuzzy;
}
}
Suppose , your date is "February 04, 2011 19:00:00"
function formatDate(date) {
var d = new Date(date);
var hh = d.getHours();
var m = d.getMinutes();
var s = d.getSeconds();
var dd = "AM";
var h = hh;
if (h >= 12) {
h = hh-12;
dd = "PM";
}
if (h == 0) {
h = 12;
}
m = m<10?"0"+m:m;
s = s<10?"0"+s:s;
/* if you want 2 digit hours:
h = h<10?"0"+h:h; */
var pattern = new RegExp("0?"+hh+":"+m+":"+s);
var replacement = h+":"+m;
/* if you want to add seconds
replacement += ":"+s; */
replacement += " "+dd;
return date.replace(pattern,replacement);
}
alert(formatDate("February 04, 2011 12:00:00"));

Output all dates of a year

I would like to list all dates and hour of a year with format mmddhh
Q1: Why I got "undefined" before the output? How can I fix it?
var m, d, h, month, day, hour, output;
for (m = 1; m <= 12; m++) {
month = addZero(m).toString();
for (d = 1; d <= 31; d++) {
day = addZero(d).toString();
for (h = 1; h <= 24; h++) {
hour = addZero(h).toString();
output += month + day + hour + "<br>";
}
}
}
document.getElementById("result").innerHTML = output;
function addZero(z) {
var z
if (z < 10)
return "0" + z;
else
return z;
}
<p id="result"></p>
Q2: I tried looping d 31 times using if (m = "01" || "03" || "05" || "07" || "08" || "10" || "12") else looping 30 times. However it is fail, how can I do that?
var m, d, h, month, day, hour, output;
for (m = 1; m <= 12; m++) {
month = addZero(m).toString();
if (m = "01" || "03" || "05" || "07" || "08" || "10" || "12") {
for (d = 1; d <= 31; d++) {
day = addZero(d).toString();
for (h = 1; h <= 24; h++) {
hour = addZero(h).toString();
output += month + day + hour + "<br>";
}
}
} else {
for (d = 1; d <= 30; d++) {
day = addZero(d).toString();
for (h = 1; h <= 24; h++) {
hour = addZero(h).toString();
output += month + day + hour + "<br>";
}
}
}
}
document.getElementById("result").innerHTML = output;
function addZero(z) {
var z
if (z < 10)
return "0" + z;
else
return z;
}
<p id="result"></p>
You have declared a variable called output, but it is not initialized with a value, so its value is undefined.
Then when you say output += month + day + hour + "<br>"; it is really output = undefined + month + day + hour + "<br>";, thus you are getting an undefined at the beginning of the output
var m, d, h, month, day, hour, output = "";
for (m = 1; m <= 12; m++) {
month = addZero(m).toString();
for (d = 1; d <= 31; d++) {
day = addZero(d).toString();
for (h = 1; h <= 24; h++) {
hour = addZero(h).toString();
output += month + day + hour + "<br>";
}
}
}
document.getElementById("result").innerHTML = output;
function addZero(z) {
var z
if (z < 10)
return "0" + z;
else
return z;
}
<p id="result"></p>

Javascript Countdown from 8am-9pm

I have a Javascript countdown from 12am to 9pm each day and then resets itself.
I want the countdown to go from 8am-9pm instead of 12am-9pm. I have been fiddling with this but I can't seem to make it work with a start time other than the defaulted 12am.
My question is how can I make the countdown from 8-21 hours instead of 0-21 hours?
Javascript:
if (document.getElementById('countdown')) {
pad = function(n, len) { // leading 0's
var s = n.toString();
return (new Array( (len - s.length + 1) ).join('0')) + s;
};
function countDown(){
var now = new Date();
if ( (now.getDay() >= 1) && (now.getDay() <= 7) ) { // Monday to Sunday
var target = 21; // 21:00hrs is the cut-off point
if (now.getHours() < target) { //
var hrs = (target - 1) - now.getHours();
if (hrs < 0) hrs = 0;
var mins = 59 - now.getMinutes();
if (mins < 0) mins = 0;
var secs = 59 - now.getSeconds();
if (secs < 0) secs = 0;
var str = pad(hrs, 2) + ':' + pad(mins, 2) + '.<small>' + pad(secs, 2) + '</small>';
document.getElementById('countdown').innerHTML = str;
}
else
$('.wereOpen').hide();
}
}
var timerRunning = setInterval('countDown()', 1000);
}
Website
I don't fully understand your question, but could you just add now.getHours() >= 7 to your if statement, i.e.
...
if (now.getHours() >= 7 && now.getHours() < target) {
...
} else {
$('.wereOpen').hide();
}
...
EDIT
In light of the comment, the following should work:
if (document.getElementById('countdown')) {
pad = function(n, len) { // leading 0's
var s = n.toString();
return (new Array( (len - s.length + 1) ).join('0')) + s;
};
function countDown(){
var now = new Date();
if ( (now.getDay() >= 1) && (now.getDay() <= 7) ) { // Monday to Sunday
var target = 21; // 21:00hrs is the cut-off point
var hours = now.getHours(); //get hours
if(hours < 8 || hours >= target) {
$('.wereOpen').hide();
return;
} else
$('.wereOpen').show();
var hrs = (target - 1) - hours;
if (hrs < 0) hrs = 0;
var mins = 59 - now.getMinutes();
if (mins < 0) mins = 0;
var secs = 59 - now.getSeconds();
if (secs < 0) secs = 0;
var str = pad(hrs, 2) + ':' + pad(mins, 2) + '.<small>' + pad(secs, 2) + '</small>';
document.getElementById('countdown').innerHTML = str;
}
}
var timerRunning = setInterval('countDown()', 1000);
}

add/subtract business days in Javascript

I need a Date.prototype.addBusDays function
that'll take an integer as the number of working days to add to the date.
However, there are two considerations: 1. Weekends, 2. Holidays (which I imagine would be a preset array to compare against. If beginning date and end date contain 3 holidays, then you push out the end date by 3)
I have come across some scripts online, one dilemma I can think of is, lets say you address all the weekends first, then you do the holidays, what if you +1 day (due to holiday), and your end date is pushed into a weekends again...<
Any ideas?
Thanks!
EDIT:
This is a part of a scheduling tool I am developing, which mean the dates will be tied to tasks which are linked together. Adding 1 day to a task, will trigger a recalculation of everything tied to it, potentially all dates in the database.
Datageek's solution helped me but I needed to augment it. This still doesn't do holidays but does do working days with the option of including Sat and/or Sun, and does support adding negative days:-
function AddWorkingDays(datStartDate, lngNumberOfWorkingDays, blnIncSat, blnIncSun) {
var intWorkingDays = 5;
var intNonWorkingDays = 2;
var intStartDay = datStartDate.getDay(); // 0=Sunday ... 6=Saturday
var intOffset;
var intModifier = 0;
if (blnIncSat) { intWorkingDays++; intNonWorkingDays--; }
if (blnIncSun) { intWorkingDays++; intNonWorkingDays--; }
var newDate = new Date(datStartDate)
if (lngNumberOfWorkingDays >= 0) {
// Moving Forward
if (!blnIncSat && blnIncSun) {
intOffset = intStartDay;
} else {
intOffset = intStartDay - 1;
}
// Special start Saturday rule for 5 day week
if (intStartDay == 6 && !blnIncSat && !blnIncSun) {
intOffset -= 6;
intModifier = 1;
}
} else {
// Moving Backward
if (blnIncSat && !blnIncSun) {
intOffset = intStartDay - 6;
} else {
intOffset = intStartDay - 5;
}
// Special start Sunday rule for 5 day week
if (intStartDay == 0 && !blnIncSat && !blnIncSun) {
intOffset++;
intModifier = 1;
}
}
// ~~ is used to achieve integer division for both positive and negative numbers
newDate.setTime(datStartDate.getTime() + (new Number((~~((lngNumberOfWorkingDays + intOffset) / intWorkingDays) * intNonWorkingDays) + lngNumberOfWorkingDays + intModifier)*86400000));
return newDate;
}
Have a look at the following implementation. Sourced from about.com
addWeekdays = function(date, dd) {
var wks = Math.floor(dd/5);
var dys = dd.mod(5);
var dy = this.getDay();
if (dy === 6 && dys > -1) {
if (dys === 0) {dys-=2; dy+=2;}
dys++; dy -= 6;
}
if (dy === 0 && dys < 1) {
if (dys === 0) {dys+=2; dy-=2;}
dys--; dy += 6;
}
if (dy + dys > 5) dys += 2;
if (dy + dys < 1) dys -= 2;
date.setDate(date.getDate()+wks*7+dys);
}
var date = new Date();
addWeekdays(date, 9);
(Updated) I've put this algorithm through its paces and it seems stable, though it does use recursion for holiday processing:
holidays = [new Date("2/13/2019"), new Date("2/19/2019")];
function addWorkdays(workdays, startDate) {
//Make adjustments if the start date is on a weekend
let dayOfWeek = startDate.getDay();
let adjustedWorkdays = Math.abs(workdays);
if (0 == dayOfWeek || 6 == dayOfWeek) {
adjustedWorkdays += (Math.abs((dayOfWeek % 5) + Math.sign(workdays)) % 2) + 1;
dayOfWeek = (dayOfWeek - 6) * -1;
}
let endDate = new Date(startDate);
endDate.setDate(endDate.getDate() + (((Math.floor(((workdays >= 0 ? dayOfWeek - 1 : 6 - dayOfWeek) + adjustedWorkdays) / 5) * 2) + adjustedWorkdays) * (workdays < 0 ? -1 : 1)));
//If we cross holidays, recompute our end date accordingly
let numHolidays = holidays.reduce(function(total, holiday) { return (holiday >= Math.min(startDate, endDate) && holiday <= Math.max(startDate, endDate)) ? total + 1 : total; }, 0);
if (numHolidays > 0) {
endDate.setDate(endDate.getDate() + Math.sign(workdays));
return addWorkdays((numHolidays - 1) * Math.sign(workdays), endDate);
} else return endDate;
}
I expanded on khellendros74's answer for a project of mine that needed to disable Sundays and mailing holidays in the datepicker and return two dates on press of a button: three business days (i.e. non-holiday and non-Sunday) after the date picked in the datepicker (a field with an id of "calendar") and six business days after the date picked in the datepicker and then put those two results into a couple of disabled input fields (handDelivered and mailed). The button press calls the function calculateDates. Here is that code:
var disabledDates = ['11/11/2015', '11/26/2015', '12/25/2015', '01/01/2016','01/18/2016', '02/15/2016','05/30/2016', '07/04/2016','09/05/2016','10/10/2016','11/11/2016','11/24/2016', '12/26/2016','01/02/2017','01/16/2017', '02/20/2017','05/29/2017', '07/04/2017','09/04/2017','10/09/2017','11/10/2017','11/23/2017', '12/25/2017','01/01/2018','01/15/2018', '02/19/2018','05/28/2018', '07/04/2018','09/03/2018','10/08/2018','11/12/2018','11/22/2018', '12/25/2018','01/01/2019','01/21/2019', '02/18/2019','05/27/2019', '07/04/2019','09/02/2019','10/14/2019','11/11/2019','11/28/2019', '12/25/2019','01/01/2020','01/20/2020', '02/17/2020','05/25/2020', '07/03/2020','09/07/2020','10/11/2020','11/26/2020','11/26/2020', '12/25/2020'];
$(function(){
$('#calendar').datepicker({
dateFormat: 'mm/dd/yy',
beforeShowDay: editDays
});
function editDays(date) {
for (var i = 0; i < disabledDates.length; i++) {
if (new Date(disabledDates[i]).toString() == date.toString() || date.getDay() == 0) {
return [false];
}
}
return [true];
}
});
function calculateDates()
{
if( !$('#calendar').val()){
alert("Please enter a date.");
document.getElementById('calendar').focus();
return false;
}
var dayThreeAdd = 0;
var daySixAdd = 0;
for (var i = 0; i < disabledDates.length; i++) {
var oneDays = AddWorkingDays($('#calendar').val(),1,true,false);
var twoDays = AddWorkingDays($('#calendar').val(),2,true,false);
var threeDays = AddWorkingDays($('#calendar').val(),3,true,false);
var fourDays = AddWorkingDays($('#calendar').val(),4,true,false);
var fiveDays = AddWorkingDays($('#calendar').val(),5,true,false);
var sixDays = AddWorkingDays($('#calendar').val(),6,true,false);
if (new Date(disabledDates[i]).toString() == oneDays.toString()) {
dayThreeAdd++;
daySixAdd++;
}
if (new Date(disabledDates[i]).toString() == twoDays.toString()) {
dayThreeAdd++;
daySixAdd++;
}
if (new Date(disabledDates[i]).toString() == threeDays.toString()) {
dayThreeAdd++;
daySixAdd++;
}
if (new Date(disabledDates[i]).toString() == fourDays.toString()) {
daySixAdd++;
}
if (new Date(disabledDates[i]).toString() == fiveDays.toString()) {
daySixAdd++;
}
if (new Date(disabledDates[i]).toString() == sixDays.toString()) {
daySixAdd++;
}
}
var threeDays = AddWorkingDays($('#calendar').val(),(3 + dayThreeAdd),true,false);
var sixDays = AddWorkingDays($('#calendar').val(),(6 + daySixAdd),true,false);
$('#handDelivered').val((threeDays.getMonth()+1) + '/' + threeDays.getDate() + '/' + (threeDays.getYear()+1900));
$('#mailed').val((sixDays.getMonth()+1) + '/' + sixDays.getDate() + '/' + (sixDays.getYear()+1900));
}
function AddWorkingDays(datStartDate, lngNumberOfWorkingDays, blnIncSat, blnIncSun) {
datStartDate = new Date(datStartDate);
var intWorkingDays = 5;
var intNonWorkingDays = 2;
var intStartDay = datStartDate.getDay(); // 0=Sunday ... 6=Saturday
var intOffset;
var intModifier = 0;
if (blnIncSat) { intWorkingDays++; intNonWorkingDays--; }
if (blnIncSun) { intWorkingDays++; intNonWorkingDays--; }
var newDate = new Date(datStartDate)
if (lngNumberOfWorkingDays >= 0) {
// Moving Forward
if (!blnIncSat && blnIncSun) {
intOffset = intStartDay;
} else {
intOffset = intStartDay - 1;
}
// Special start Saturday rule for 5 day week
if (intStartDay == 6 && !blnIncSat && !blnIncSun) {
intOffset -= 6;
intModifier = 1;
}
} else {
// Moving Backward
if (blnIncSat && !blnIncSun) {
intOffset = intStartDay - 6;
} else {
intOffset = intStartDay - 5;
}
// Special start Sunday rule for 5 day week
if (intStartDay == 0 && !blnIncSat && !blnIncSun) {
intOffset++;
intModifier = 1;
}
}
// ~~ is used to achieve integer division for both positive and negative numbers
newDate.setTime(datStartDate.getTime() + (new Number((~~((lngNumberOfWorkingDays + intOffset) / intWorkingDays) * intNonWorkingDays) + lngNumberOfWorkingDays + intModifier)*86400000));
return newDate;
}
Simple solution to solve the whole problem; you can just loop through the days to skip weekdays and holidays:
Date.prototype.holidays = {
// fill in common holidays
all: [
'0101', // Jan 01
'1225' // Dec 25
],
2016: [
// add year specific holidays
'0104' // Jan 04 2016
],
2017: [
// And so on for other years.
]
};
Date.prototype.addWorkingDays = function(days) {
while (days > 0) {
this.setDate(this.getDate() + 1);
if (!this.isHoliday()) days--;
}
return this;
};
Date.prototype.substractWorkingDays = function(days) {
while (days > 0) {
this.setDate(this.getDate() - 1);
if (!this.isHoliday()) days--;
}
return this;
};
Date.prototype.isHoliday = function() {
function zeroPad(n) {
n |= 0;
return (n < 10 ? '0' : '') + n;
}
// if weekend return true from here it self;
if (this.getDay() == 0 || this.getDay() == 6) {
return true;
}
var day = zeroPad(this.getMonth() + 1) + zeroPad(this.getDate());
// if date is present in the holiday list return true;
return !!~this.holidays.all.indexOf(day) ||
(this.holidays[this.getFullYear()] ?
!!~this.holidays[this.getFullYear()].indexOf(day) : false);
};
// Uasage
var date = new Date('2015-12-31');
date.addWorkingDays(10);
alert(date.toDateString()); // Mon Jan 18 2016
date.substractWorkingDays(10);
alert(date.toDateString()) // Thu Dec 31 2015
This only takes weekends into account and not holidays, but it's a start...
function mod(x, y) {
// https://stackoverflow.com/a/4467559/2173455
return ((x % y) + y) % y;
}
function calculateDateDiff(date, diff) {
let returnDate = new Date(date.getTime());
let daysLeftToAdd = Math.abs(diff);
let weekendDays = 0;
let weekDay = returnDate.getDay();
while(daysLeftToAdd >= 0) {
if(weekDay == 0 || weekDay == 6) {
weekendDays++;
}
else {
daysLeftToAdd--;
}
weekDay = mod(diff > 0 ? weekDay + 1 : weekDay - 1, 7);
}
returnDate.setDate(diff > 0 ?
returnDate.getDate() + diff + weekendDays :
returnDate.getDate() + diff - weekendDays
);
return returnDate;
}

Categories