Display next 5 days excluding Sundays in javascript - javascript

I am displaying the following code for next 5 days
function setDateTime() {
var timesOffice = (officeTimes[officeID] + "").split(",");
//alert(officeTimes[officeID]+":12:"+timesOffice[0]);
var dt = new Date(correctDate);
var dateOptions = "";
var firstdateString = "";
var totalDays = 5;
for (i = 0; i < totalDays; i++) {
var sateString = dt.getFullYear() + " " + monthNames[dt.getMonth()] + " " + (dt.getDate());
//console.log("i:"+i+"s:"+sateString);
dateFlag = 0;
var j = 0;
for (j = 0; j < timesOffice.length; j++) {
if (checkValidDateTime(sateString, timesOffice[j])) {
dateFlag = 1;
break;
}
}
dt.setDate(dt.getDate() + 1);
if (dateFlag == 0) {
totalDays++;
continue;
}
if (firstdateString == "") firstdateString = sateString;
dateOptions = dateOptions + '<option value="' + sateString + '">' + sateString + '</option>';
}
$(".date").html(dateOptions);
}
I want to exclude Sundays from this list

You can tell what day of the week a Date instance represents using its getDay function:
if (dt.getDay() === 0) {
// It's Sunday
}
else {
// It isn't
}
I figure you can take it from there... :-)

You can use the getDay method to get the day of the week:
function setDateTime() {
var timesOffice = (officeTimes[officeID] + "").split(",");
//alert(officeTimes[officeID]+":12:"+timesOffice[0]);
var dt = new Date(correctDate);
var dateOptions = "";
var firstdateString = "";
var totalDays = 5;
int i=0;
while(i<totalDays) {
if(dt.getDay() != 0) // exclude Sundays
{
var sateString = dt.getFullYear() + " " + monthNames[dt.getMonth()] + " " + (dt.getDate());
//console.log("i:"+i+"s:"+sateString);
dateFlag = 0;
var j = 0;
for (j = 0; j < timesOffice.length; j++) {
if (checkValidDateTime(sateString, timesOffice[j])) {
dateFlag = 1;
break;
}
}
if (firstdateString == "") firstdateString = sateString;
dateOptions = dateOptions + '<option value="' + sateString + '">' + sateString + '</option>';
i++;
}
dt.setDate(dt.getDate() + 1);
}
$(".date").html(dateOptions);
}

As T.J Crowder said, you can use Date.getDay() to get the current weekday in the week. Giving some integer from 0 to 6 where 0 is Sunday and 6 is Saturday.
To show the next weekdays I supposed we don't want to print a bunch of numbers on the screen, so we can use a weekdays array to go from numbers to their corresponding text:
var weekdays = ["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"];
Now we can just use a for loop to scroll through these, starting from the todays day you get from using .getDay(). Note that if you go over we want to go back to 0, so I'll use a separate variable j in the loop for that:
var weekdays = ["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"];
var date = new Date();
var day = date.getDay(); // Current day
var numDays = 5; // Number next days
for(var i = day; i <= day + numDays; i++ ) {
var j = i;
j = j % weekdays.length;
console.log(weekdays[j]);
}
To show it can overflow and move back to Sunday, Here is a fiddle that prints the next 20 days.
To exclude Sunday, simply check that if(j != 0) , then print:
for(var i = day; i <= day + numDays; i++ ) {
var j = i;
j = j % weekdays.length;
if( j != 0 )
console.log(weekdays[j]); // Only prints non-Sundays
}
Although since today is Sunday, suppose you want to include Today's Sunday, but not the next Sundays. Simply change the if statement to if( j != 0 || i == 0 ), which will make an exception for the first element. Here is an example of that.

Related

How to create a list of weeks/months/quarters between a range of two dates

Based on a date range, I am trying to create four lists of strings with weeks, months, quarters, and year that are formated in a specific way.
The below code is working fine (please note the special way of calculating the weeks. That is intended).
My problem is that the implementation fails as soon as the dateEnd is defined to be in the following year (eg 03-28-2019). Then, the generated lists become incomplete/incorrect.
Is there a better approach to achieve the goal?
Here is a fiddle... https://jsbin.com/wipehahigo/1/edit?html,js,console
dateStart = "01-01-2018";
dateEnd = "03-28-2018";
//get list of week strings
lowerRange = Math.ceil(moment(dateStart, "MM-DD-YYYY").dayOfYear()/7);
upperRange = Math.ceil(moment(dateEnd, "MM-DD-YYYY").dayOfYear()/7);
year = moment(dateStart, "MM-DD-YYYY").year();
weekList = []
for (var i = lowerRange; i <= upperRange; i++) {
weekList.push('W' + i + '_' + year);
}
//get list of month strings
lowerRange = moment(dateStart, "MM-DD-YYYY").month()+1;
upperRange = moment(dateEnd, "MM-DD-YYYY").month()+1;
year = moment(dateStart, "MM-DD-YYYY").year();
monthList = []
for (var i = lowerRange; i <= upperRange; i++) {
monthList.push('M' + i + '_' + year);
}
//get list of quarter strings
lowerRange = moment(dateStart, "MM-DD-YYYY").quarter();
upperRange = moment(dateEnd, "MM-DD-YYYY").quarter();
year = moment(dateStart, "MM-DD-YYYY").year();
quarterList = []
for (var i = lowerRange; i <= upperRange; i++) {
quarterList.push('Q' + i + '_' + year);
}
//get list of year strings
lowerRange = moment(dateStart, "MM-DD-YYYY").year();
upperRange = moment(dateEnd, "MM-DD-YYYY").year();
yearList = []
for (var i = lowerRange; i <= upperRange; i++) {
yearList.push('Y' + i + '_' + year);
}
console.log(weekList);
console.log(monthList);
console.log(quarterList);
console.log(yearList);
Update and Solution
I doing this now... https://jsbin.com/mepifevico/1/edit?html,js,console
window['moment-range'].extendMoment(moment);
weekList = [];
monthList = [];
quarterList = [];
yearList = [];
dateStart = "01-01-2018";
dateEnd = "03-28-2019";
dateStart = moment(dateStart, 'MM-DD-YYYY');
dateEnd = moment(dateEnd, 'MM-DD-YYYY');
dateRange = moment.range(dateStart, dateEnd);
for (let d of dateRange.by('week')) {
weekNumber = Math.ceil(d.dayOfYear()/7);
year = d.year();
weekList.push('W' + weekNumber + '_' + year);
}
for (let d of dateRange.by('month')) {
monthNumber = d.month() + 1;
year = d.year();
monthList.push('M' + monthNumber + '_' + year);
}
for (let d of dateRange.by('quarter')) {
quarterNumber = d.quarter();
year = d.year();
quarterList.push('Q' + quarterNumber + '_' + year);
}
for (let d of dateRange.by('year')) {
yearNumber = d.year();
year = d.year();
yearList.push('Y' + yearNumber + '_' + year);
}
console.log(weekList)
console.log(monthList)
console.log(quarterList)
console.log(yearList)
To make your calculations work across multiple years, you should base them not on the endDate, but on the duration between the two dates. To do so, you can make your for loops going from the startDate to the startDate + duration.
I made an example for the calculation of the weeks : https://jsbin.com/xejocusana/edit?html,js,console
dateStart = "01-01-2018";
dateEnd = "03-31-2019";
start = moment(dateStart, "MM-DD-YYYY")
end = moment(dateEnd, "MM-DD-YYYY")
lowerRange = Math.floor(moment(dateStart, "MM-DD-YYYY").dayOfYear()/7);
// calculate the number of weeks between the two dates
numberOfWeeks = end.diff(start, 'weeks');
year = moment(dateStart, "MM-DD-YYYY").year();
weekListA = []
for (var i = lowerRange; i <= lowerRange + numberOfWeeks; i++) {
weekListA.push('W' + (i%52 +1) + '_' + (year+ Math.floor(i/52)));
}
console.log(weekListA);
I added :
a calculation of the numberOfWeeks, needed for the limit of the loop ;
a modulo + (i%52 +1) in the loop, to have the number of the week (You have to write +1 to make it begin at 0. Due to this constraint, you have to use Math.floor() instead of Math.ceil() when you calculate lowerRange) ;
a + Math.floor(i/52) in the loop, to increment the number of the year ;
I let you check if all the cases are covered (dates across more than 2 years, dates included or excluded, etc.)
It's just for the weekList but you should be able to figured it out for the rest :
lowerRange = moment(dateStart, "MM-DD-YYYY").week();
upperRange = moment(dateEnd, "MM-DD-YYYY").week();
year = moment(dateStart, "MM-DD-YYYY").year();
year2 = moment(dateEnd, "MM-DD-YYYY").year();
//add extra weeks to upperRange if the date range > 12 months
upperRange += (year2-year)*52-lowerRange;
weekList = []
for (var i = lowerRange; i <= upperRange; i++) {
//some fix to show the year
weekList.push('W' + (i-lowerRange) + '_' + (year+Math.floor((i-lowerRange)/12)));
}

How to get minutes on timestamp in jquery

I'd like to get a current timestamp object which is minutes l。 How do I do it with JavaScript?
Here my code :
var mins = "";
var new_timestamp = parseInt($("#current_time").data("timestamp")) + 1000;
var date = new Date(new_timestamp);
for (var b = 0; b < 60; b++) {
if (b == date.getMinutes()) {
str += "<option selected>" + (b < 10 ? ("0" + b) : b) + "</option>";
} else {
str += "<option>" + (b < 10 ? ("0" + b) : b) + "</option>";
}
}
$("#bank-order-time [name=\"minutes\"]").html(mins);
HTML :
<select name="minutes">
var date = new Date();
new Date() gives you a Date object of then time. You don't need to input a timestamp.
And date.getMinutes() give you the minute as you already know.
And if you need to get the current time again, remember you need to create a new Date object and do not use the old one.
My answer:
(function(){
var str ="";
var new_timestamp = parseInt($("#current_time").data("timestamp"))+1000;
var date = new Date(new_timestamp);
for( var a = 0; a < 24 ; a++)
{
if( a== date.getHours() )
{
str +="<option selected>"+(a<10?("0"+a):a)+"</option>" ;
}
else
{
str +="<option>"+(a<10?("0"+a):a)+"</option>" ;
}
}
$("#bank-order-time [name=\"hour\"]").html(str);
var mins = "";
for( var b = 0; b < 60; b++)
{
if( b == date.getMinutes())
{
mins +="<option selected>"+(b<10?("0"+b):b)+"</option>" ;
}
else
{
mins +="<option>"+(b<10?("0"+b):b)+"</option>" ;
}
}
$("#bank-order-time [name=\"minutes\"]").html(mins);
})();

Loading dynamic calendar to start on correct day of the month

I'm trying to get a calendar to load the days of the month on the correct starting day of whichever year is selected by user. Right now the form loads the correct month and number of days for each month, but it starts on Sunday[0], when for instance, in April, the 1st is on Friday of week 1.
I've been stuck on this for a few days, and I can't figure out what or where i'm supposed to put a loop that makes it start on the correct day, and have the previous months days blank.
var daysOfTheWeek = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
function showCalendar (mth, yr)
{
var firstDayOfMonth = mth + "/1/" + yr;
var d = new Date ( firstDayOfMonth);
var numberOfDaysInMonth = daysInMonth (d);
var firstDayOfWeek = d.getDay();
var str = "<ul>";
str += "<li>Number of days in the month: " + numberOfDaysInMonth + "</li>";
str += "<li>First day of the week: " + firstDayOfWeek + " (" + daysOfTheWeek[firstDayOfWeek] + ")</li>";
str += "</ul>";
calstr = "";
var maxCalDays = 35;
for(var i =0; i<numOfDaysInMonth; i++) {
// if there are 7 cells create string - row
if (i % 7 == 0 && i > 0) {
calstr += "<div class='row'>";
}
// increments through each cell - making up each row
calstr += "<div class='calCell'>" + (i + 1) + "</div>";
if (i % 7 == 0 && i > 0) {
calstr += "</div>";
}
}
$("#results").append(calstr);
Here is the what it looks like running.
JSFiddle
I edited your jsFiddle:
You just have to skip the days days before the first day with:
for(var j = 0; j < firstDayOfWeek; j++){
calstr += "<div class='calCell empty'></div>";
}
e.g. set css classes like this:
.calCell.empty {
border: none;
}
And then add these days to your modulo operation to have the right 7 days line break:
var maxCalDays = 35;
for(var i = 0; i < numOfDaysInMonth; i++) {
// if there are 7 cells create string - row
if((i + firstDayOfWeek) % 7 ==0 && i>0) {
calstr += "<div class='row'>";
}
...
}
Also you have to disable selecting of this empty cells with replacing your selectors .calCell with .calCell:not(.empty). E.g.:
$(".calCell:not(.empty)").click(function() {
changeColor($(this));
});
I guess you only want to show old with $("#results").html("")

Find when month appears five times in JavaScript loop (date, string)

I am building a paycheck month calculator. If you normally get paid every other week, most months will have two paychecks but two months of each year will have three paychecks.
My program works as expected, it appends to a list the date of everyday starting today (today being a Friday). Now I would like to make list items with the same month that appears five times stand out, simple coloring would work.
Can this be done with a second function for li in ul and then if li[i] string[4][6] === the next li[i][4][6] and then somehow search for five? I'm not sure how the logic would work. The reason why I picked [4][6] is because in each list item, the months are all three letter abbreviations that occupy the same part of the string.
How can this be done?
var d;
var week = 7;
function getDates() {
for (var i = 0; i < 52; i++) {
d = new Date();
d.setDate(d.getDate() + week);
$('#date').append("<li>" + d + "</li>");
week += 7;
};
}
$(document).ready(function() {
getDates();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul id="date"></ul>
A dirty example:
var d;
var week = 7;
function getDates() {
for (var i = 0; i < 52; i++) {
d = new Date();
d.setDate(d.getDate() + week);
$('#date').append("<li data-mth='"+d.getMonth()+"'>" + d + "</li>");
week += 7;
}
$('li[data-mth]').each(function(){
var $group = $('li[data-mth="'+ $(this).data("mth") +'"]');
if( $group.length > 4 ) $group.addClass("standOut");
});
}
$(getDates);
.standOut{
color:red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul id="date"></ul>
You could put dates in a array where the month is the key, then loop the months and if the count on that month == 5 colour all the dates.
var d;
var week = 7;
$(document).ready(function() {
getDates();
});
function getDates() {
var months = new Array;
for (var i = 0; i < 52; i++) {
d = new Date();
d.setDate(d.getDate() + week);
var month = d.getMonth();
if(!months[month]) months[month] = new Array;
months[month].push(d);
week += 7;
};
plot_months(months);
}
function plot_months(months){
$.each(months,function(key,month){
var style = "";
if(month.length > 4) style = "color:red;";
$.each(month,function(week,date){
$('#date').append('<li style="'+style+'">' +date+ "</li>");
});
});
}`
See this fiddle

How to create a timestamp with javascript

I want to use a timestamp as an update indicator(last updated at), so i need a current time, month/day/year/hours/minutes/seconds, but the date() returns an live value. Is there a way to do this?
UPDATE: the idea is like this http://web.student.tuwien.ac.at/~e9125168/javas/jstamp.html (this shows a last modified time, but this is for the document).
The script where i need to show a 'last updated on' time is for an jquery ajax script, which updates a certain piece of code every ... seconds/minutes.
function getPastTimestamp(t) {
var d = new Date(t);
var output = "";
var items = new Array();
var i = 0;
items[i++] = d.getMonth() + 1;
items[i++] = d.getDate();
items[i++] = d.getFullYear();
items[i++] = d.getHours();
items[i++] = d.getMinutes();
items[i] = d.getSeconds();
for (i = 0; i < items.length; i += 1) {
output += (items[i] < 10) ? "0" + items[i] : items[i];
if (i < items.length - 1) output += '/';
}
return output;
}
function getCurrentTimestamp() {
return getPastTimestamp((new Date()).getTime());
}

Categories