Splitting up a month based on number of weeks. JS - javascript

I'm working on a project in which I need to find what days are holidays, and display specific messages for those holidays.
With some holidays, like Christmas, it is simply the 25th of December. But for other holidays, such as thanksgiving, it is a little tricky in that it is the 4th Thursday in November.
The approach I'm using is splitting up which week.
day = moment()
month = day.month() + 1
weeknum = Math.floor((day - 1) / 7) + 1
holiday2 = month + "/" + weeknum + "/" + day
Today happens to be columbus day, and so based off of what I have, it should be '10/2/1'. 10th month, 2nd week, 1st day. (10/12). The problem that I am getting, is with what I have right now for holiday2, I am getting:
10/206381035675/1444667249719
So...I know technically I'm close in that I see the '10/2/1' but I am getting very large abnormal numbers.
My question is 2 fold. How would I condense the numbers so that instead of getting a 10 digit response, I would get just the 1 or two digits that I need?
Would there be a better way to approach this?

moment() returns a date object. You need to get the date similar to how you are already getting the month. You can do this using .date().
day = moment();
month = day.month() + 1;
date = day.date();
weeknum = Math.floor((date - 1) / 7) + 1;
holiday2 = month + "/" + weeknum + "/" + date;
Your current solution doesn't work because of the way dates are converted to integers. Specifically, they are stored as the number of milliseconds since 1970/01/01.
This answer suggests the best way for getting the week number:
var weeknum = Math.ceil(date / 7);

Related

Check if current time falls between a range, including "from 21:00 to 03:00"

I have two strings, dateFrom and dateTo, in format NN:NN and need to check if the current time falls between the range.
The problem is super-simple in theory, with the obvious:
const d = new Date()
const timeAsString = ("0" + d.getHours()).slice(-2) + ':' + ("0" + d.getMinutes()).slice(-2)
Once they are strings, I can easily check whether timeAsString > dateFrom && timeAsString < dateTo
However, I would like to be able to ALSO set a valid interval as timeFrom: "21:00" and timeTo: "0300" -- and the check should return true for 01:00 (the rational: the "true" interval is between 9PM and 3AM, therefore 1AM is "good").
I could code it myself but I can already see gotchas that are going to byte me in the butt in 6 months time. This screams edge cases.
Is there a common, reliable pattern for this?

PopUp Calendar Datepicker Error / December Month 12 as 00 and adding a digit to year

We have a calendar function on our site which enables people to book reservations. The calendar is visible to the user, but the date gets passed to the booking widget as CIM (check in month), CID (check in day), and CIY (check in year) with comparable dates for Check out.
All has gone well with the scripting until we have received December. It appears that month 12 is getting passed to the booking widget as month "00". I was able to see the fields passed to the form just once. 12/26/2013 and 12/27/2013 were being passed as 00/26/2014 and 00/27/2014 respectively.
I've temporarily gone to a more basic booking widget on the major pages of the site until this can be fixed, so clients can still book rooms. Unfortunately, I am a js newbee and the company I partnered with on this project has only a skeleton crew this week. I am at a loss of what might be wrong with this. [Month 12 is being passed as 00, and in December 2013 is being passed as 2014.]
Could you look at This web page upon which I've kept the broken script. You cannot use dates which have passed and the Inn will be closed from Jan 1-16, so those dates won't work. If you try any other date in 2014 it should work, except again when you get to December, it's broken.
The only thing I could find online as a help was this post which has no resolution.
Could something be added to the existing code in js/tcal.js or in my booking widget section that says (to the effect of) when converting get_month if CIM="00" or if COM="00" each of these should be renamed to "12"? Not at all sure why the script may have added a year to 2013 in my first example.
JavaScript's Date object is a little inconsistent:
month ranges from 0 - 11
day ranges from 1 - 31
For December, you're passing 12 to setMonth(), which is outside of the range for month by 1. That extra 1 is what is incrementing the next value in line, ie. year.
You can change get_nights() to decrement month, and then in pop_fields() increment month so the displayed months range from 1 - 12
function get_nights(date_array){
var check_in_date = new Date();
var check_out_date = new Date();
var check_in_month = parseInt(date_array[0]) - 1;
var check_out_month = parseInt(date_array[3]) - 1;
check_in_date.setFullYear(date_array[2]);
check_in_date.setMonth(check_in_month);
check_in_date.setDate(date_array[1]);
check_out_date.setFullYear(date_array[5]);
check_out_date.setMonth(check_out_month);
check_out_date.setDate(date_array[4]);
pop_fields(check_in_date,check_out_date);
}
function pop_fields(check_in,check_out){
var in_month = String(check_in.getMonth() + 1);
var in_date = String(check_in.getDate());
var out_month = String(check_out.getMonth() + 1);
var out_date = String(check_out.getDate());
document.getElementById('CIM').value = (in_month.length == 1) ? ('0' + in_month) : in_month;
document.getElementById('CID').value = (in_date.length == 1) ? ('0' + in_date) : in_date;
document.getElementById('CIY').value = check_in.getFullYear();
document.getElementById('COM').value = (out_month.length == 1) ? ('0' + out_month) : out_month;
document.getElementById('COD').value = (out_date.length == 1) ? ('0' + out_date) : out_date;
document.getElementById('COY').value = check_out.getFullYear();
}
Mozilla Developer Network has a good explanation and a couple of examples of this not intuitive behavior on the Date object page

Is there any way to format the date of a field in a query? [duplicate]

This question already has answers here:
Where can I find documentation on formatting a date in JavaScript?
(39 answers)
Closed 9 years ago.
I am getting a query with a field in an undesired date format (Thu Feb 21 00:00:00 EST 2013)
Is there any way to modify this to mm-dd-yyy?
I am using javascript, I found a php way to do it, but sadly it has to be in javascript, so the instruction has to be pretty much the same way it would be in TOAD.
I tried the CONVERT() method and it didn't work. I am not sure I am using it right though
The Convert() function will work, but you need to use the correct format code from here:
SQL Convert() Function.
SELECT Convert(char(10), #date, 110)
Date.js is pretty handy for date formatting.
you probably could try converting to a unix timestamp, then formatting. I havent tested this, and it will probably throw an error, but you get the idea.
var input = your date;
input = input.split(" - ").map(function (date){
return Date.parse(date+"-0500")/1000;
}).join(" - ");
var year = input.getYear();
var month = input.getMonth();
var day = input.getDay();
var hours = input.getHours();
var minutes = input.getMinutes();
var seconds = input.getSeconds();
var formatted = month + " " + day + ", " + year + " at " hours + ':' + minutes + ':' + seconds;
There are basic Date object functions in JS that you can use.
First, create the date variable:
var date = new Date('your date value');
Then you can access the individual date pieces:
var month = date.getMonth() + 1; //gets the month . . . it's 0-based, so add 1
var day = date.getDate(); //gets the day of the month
var year = date.getFullYear(); //gets the 4-digit year
Once you have those values, you can concatenate them in any format that you'd like. For a basic mm-dd-yyyy, use:
var formattedDate = month + "-" + day + "-" + year;
There time and timezone values are also available.
That's a badly mixed up format. There are two basic ways to modify it, one is to just re–order the bits you have, the other is to convert it to a date object and use that to create the new string. Either way, you haven't said what to do with the timezone offset.
Using abbreviations or names for timezones is ambiguous, there is no standard for them and some are duplicted (EST is used for three different timezones). In any case, a simple re–ordering can be:
function formatDate(s) {
var months = {jan:'01', feb:'02', mar:'03', apr:'04',
may:'05', jun:'06', jul:'07', aug:'08',
sep:'09', oct:'10', nov:'11', dec:'12'};
var s = s.split(' ');
var d = (s[2] < 10? '0' : '') + s[2];
return months[s[1].toLowerCase()] + '-' + d + '-' + s[5];
}
alert(formatDate('Thu Feb 21 00:00:00 EST 2013')); // 02-21-2013
The output format (mm-dd-yyyy) is ambiguous, consider using something like 21-Feb-2013 or a standard format like ISO8601 (2013-02-21).
If you need to consider the timezone, it will be easier to create a date object, add the offset, then get back the new date. However, you will also need to work out how to convert the string timezone to a number (preferably minutes, but hours is OK) that can be used with the date.

How to efficiently calculate consecutive dates given an original date

This is for a system that essentially allows you to set the first date for a given event, then to set the recurrence period.
Eg. I set a date for a week from now, 19/07/2012, so I know that I have to put the cat out with the milk. I also set it to be a weekly notification, so in future weeks I want to be notified of the same.
That original date sits in my database, which is fine for week 1, but in week 2 I need to return the date as the original plus 1 week.
On the face of it, that may seem straightforward, but I need to make sure I can account for leap years and different recurrence frequencies (fortnightly, monthly, yearly, whatever).
I'd like to keep this as a javascript implementation - because it's quicker and I feel probably would require less code than updating dates in the database. Maybe it's not achievable, any pointers would be excellent.
I think these may be a starting point:
Given a start date , how to calculate number of years till current date in javascript
Given a date, how can I efficiently calculate the next date in a given sequence (weekly, monthly, annually)?
Update, I've written the below to return the amount of time to add in each different case, from there I can just use the answer below:
var strDate = $(this).find('.next').text();
var frequency = $(this).find('.occurs').text();
var frmDate = getDateObject(strDate);
var toDate = new Date();
var days = parseInt(Math.floor((frmDate - toDate) / 86400000));
if(days < 0) {
// find out how many WHOLE 'frequencies' have passed
var weeks = Math.ceil(0 - (days / 7));
var months = Math.ceil(0 - (monthDiff(toDate,frmDate)));
var years = Math.ceil(months / 12);
//alert(days + '/' + weeks + '/' + fortnights + '/' + months + '/' + quarters + '/' + years);
if(frequency == 'Weekly') { frmDate.add(weeks).weeks(); }
if(frequency == 'Fortnightly') { frmDate.add(weeks*2).weeks(); }
if(frequency == 'Monthly') { frmDate.add(months).months(); }
if(frequency == 'Quarterly') { frmDate.add(months*3).months(); }
if(frequency == 'Annually') { frmDate.add(years).years(); }
var newdate = frmDate.toString("dd/MM/yyyy");
//alert(newdate);
$(this).find('.next').text(newdate);
}
Also, the SQL implementation for this would be using DATEADD:
http://sql-plsql.blogspot.com/2010/07/dateadd.html
You don't have to worry about special dates like leap year and so forth, because most Date functions take care of that.
Alternatively, you can use the getDate(), getMonth() as the other user suggested.
var today = new Date();
today.setDate(today.getDate() + numberOfDaysToAdd);
What I would do (probably not the best solution, I'm just coming up with it right now) is to start from the initial date and use a loop: while the date you are observing is less than the current date, increment the observed date by a week (fortnight, month, year etc.). If you land on the current date, the event happens. Otherwise it's for another day.
You can use things like date.setDate(date.getDate()+1); to increment the date by a day, the same +7 for a week, using set/getMonth and set/getFullYear for months and years respectively. If you give a value out of bounds, JS will wrap it (so March 32nd becomes April 1st)
Please check out the following code for some raw idea
var someDate = new Date();
for(var i = 0 ; i < 7 ; i++)
{
someDate.setDate(someDate.getDate() + 1);
console.log(someDate)
}
You can test the same in the below fiddle
Consecutive 7 days from current day

Disallow dates with JavaScript using Drop Down boxes for MM, DD and YYYY

I'm working on a mobile website and have drop down boxes for the Month, Date and Year. I'm needing something disallow them to continue to the next step if they chose a past date. I've seen calendar controls that do this but I'm not wanting to use a calendar control. I've spent the better part of the day looking for something but haven't been able to find anything. Does anyone have something like this or know of something that maybe I'm missing?
function date_check()
{
var trans_date = document.form1.selectmonth.options[document.form1.selectmonth.selectedIndex].value + "-" + document.form1.selectday.options[document.form1.selectday.selectedIndex].value + "-" + document.form1.selectyear[document.form1.selectyear.selectedIndex].value;
var d = new Date();
var today = (d.getMonth()+1) + "-" + d.getDate() + "-" + d.getFullYear();
if(new Date(trans_date) < new Date(today)){
alert("The shipping date cannot be in the past, please enter a valid shipping date.");
return false;
}
}
This is what I came up with but it's not working. Am I missing something else? I'll leave it selected as January 1 2011 and it doesnt throw the alert.
Simply get the selected values from the elements in question, concatenate the values with "-" or "/" and use the Date constructor to create a date object - compare that with the current date - if it is less than the current date, then fail.
// Inside your form's validation handler ...
var year, month, day, provided_date, now = new Date();
// Remove the hours, minutes and seconds from the now timestamp
now = new Date(now.getYear(), now.getMonth(), now.getDate());
// Get your year select - document.getElementById
// or any other method you have available
year = your_year_select.options[your_year_select.selectedIndex].value;
// and so on for month and day
// Remember, month is 0 indexed in JavaScript (January is month 0)
// so make sure your dropdown values take account of this.
// Otherwise, use month - 1 here.
provided_date = new Date(year, month, day);
// if all you need to do is validate the date
return provided_date >= now;
It sounds like you just need a validation function that creates a new date from the selected inputs and compares it to the current date. Something like:
function isFutureDate(year, month, day) {
return (Date.parse("" + year + "-" + month + "-" + day)) - new Date() > 0;
}
Except that you'll probably need to account for the timezone shift.

Categories