Javascript - array override - javascript

I am writing a function to 'calculate' the dates of a working week based on the current date.
Console.log of the array's item is correct in the cycle, but when I print the content of the array at the end of the cycle, all the items have the same value.
I can't figure out what's wrong in my logic.
Any hing is much appreciated.
function calculateWorkingDays(){
var weekDates = ["0","1","2","3","4","5","6"];
var currentDate = new Date();
var weekDay = currentDate.getDay();
console.log("Initial weekDay: " + weekDay);
for (var i=0; i<7; i++){
console.log(i);
//check for Sunday (0)
if (weekDay==0){
weekDates[currentDate.getDay()] = currentDate;
//console.log("if i=0: day" + currentDate.getDay());
console.log("date: " + currentDate);
console.log("day: " + currentDate.getDay());
console.log("weekDates" + currentDate.getDay() + " " + weekDates[currentDate.getDay()]);
//set to Monday (1)
weekDay = 1;
currentDate.setDate(currentDate.getDate()-6);
} else {
if (weekDay<6) {
weekDates[currentDate.getDay()] = currentDate;
console.log("date: " + currentDate);
console.log("day: " + currentDate.getDay());
console.log("weekDates" + currentDate.getDay() + " " + weekDates[currentDate.getDay()]);
weekDay = weekDay + 1;
} else {
weekDates[currentDate.getDay()] = currentDate;
console.log("date: " + currentDate);
console.log("day: " + currentDate.getDay());
console.log("weekDates" + currentDate.getDay() + " " + weekDates[currentDate.getDay()]);
// set to Sunday (0)
weekDay = 0 ;
}
currentDate.setDate(currentDate.getDate()+1);
}
}
console.log(weekDates.toString());
}

The problem is that you fill weekDates array with the same content - DateTime object (stored in currentDate variable). And this incrementing line...
currentDate.setDate(currentDate.getDate()+1);
... doesn't assign a new object in currentDate - it augments the existing one instead.
The solution is: either clone or serialize this object (it depends on what you're going to do with it after).
As a sidenote, your approach can be simplified: instead of checking the dates inside the loop, just start the loop always from Monday. For example:
var currentDate = new Date();
var weekDay = currentDate.getDay();
if (weekDay === 0) {
weekDay = 7;
}
currentDate.setDate(currentDate.getDate() - (weekDay - 1));
var weekDays = [currentDate];
var currentTimestamp = +currentDate;
var msInDay = 1000 * 24 * 60 * 60;
for (var i = 1; i < 7; i++) {
weekDays.push(new Date(currentTimestamp + i * msInDay));
}
console.log(weekDays);
This code stores objects in an array; if that's not necessary, just serialize (with toString() or any other method fitting your needs) the stored DateTimes.

Related

Javascript convert date to roman date

I have the following code that converts a date input into a roman date:
function romanize (num) {
if (!+num)
return false;
var digits = String(+num).split(""),
key = ["","C","CC","CCC","CD","D","DC","DCC","DCCC","CM",
"","X","XX","XXX","XL","L","LX","LXX","LXXX","XC",
"","I","II","III","IV","V","VI","VII","VIII","IX"],
roman = "",
i = 3;
while (i--)
roman = (key[+digits.pop() + (i * 10)] || "") + roman;
return Array(+digits.join("") + 1).join("M") + roman;
}
$(document).on("change",'#date', function() {
var date = new Date($('#date').val());
day = date.getDate();
month = date.getMonth() + 1;
year = date.getFullYear();
var strRomanDate = romanize(month) + " " + romanize(day) + " " + romanize(year);
$('#romandate .date').html(strRomanDate);
});
Now, this is working fine for some dates, for ex:
10/04/2018 --> X IV MMXVIII
But when I want to select a day after 12, so 13, 14,... It returns false false false.
Anyone have an idea what I should change in my code to make it work for every date?

Set validation to check two dates with javascript

I am trying to find the difference between two dates,when the user wants to change arrival date, remember the number of days between arrival/departure before the change , after changing arrival date , automatically set departure date to be x days after arrival date ,
So, if i have 01JUN17 - 05JUN17 (4days) and the user changes the arrival date to 04JUN17 then set departure to 08JUN17 (+4 days)
function changedDate() {
var startDate = $("#Arrival").val().split("-");
var endDate = $("#Departure").val().split("-");
var arrivalDate = new Date(startDate[2], startDate[1] - 1, startDate[0]);
var departureDate = new Date(endDate[2], endDate[1] - 1, endDate[0]);
var timeDiff = Math.abs(departureDate.getDate() - arrivalDate.getDate());
var diffDays = Math.ceil(timeDiff / (1000 * 3600 * 24));
if (arrivalDate >= departureDate) {
var arrDate = arrivalDate;
arrDate.setDate(arrDate.getDate() + 1);
var month = arrDate.getMonth() + 1;
if (month < 10)
month = '0' + month;
var day = arrDate.getDate();
if (day < 10)
day = '0' + day;
var year = arrDate.getFullYear();
$("#Departure").val(day + '-' + month + '-' + year);
}
if (timeDiff > 1) {
var arrDate = arrivalDate;
var depDate = departureDate;
arrDate.setDate(arrDate.getDate());
depDate.setDate(depDate.getDate() + diffDays);
var month = arrDate.getMonth() + 1;
if (month < 10)
month = '0' + month;
var day = arrDate.getDate();
if (day < 10)
day = '0' + day;
var year = arrDate.getFullYear();
var monthd = depDate.getMonth() + 1;
if (monthd < 10)
monthd = '0' + month;
var dayd = depDate.getDate();
if (dayd < 10)
dayd = '0' + day;
var yeard = depDate.getFullYear();
$("#Arrival").val(day + '-' + month + '-' + year);
$("#Departure").val(dayd + '-' + monthd + '-' + yeard);
}
if(arrivalDate < departureDate) {
var arrDate = arrivalDate;
arrDate.setDate(arrDate.getDate() + 1);
var month = arrDate.getMonth() + 1;
if (month < 10)
month = '0' + month;
var day = arrDate.getDate();
if (day < 10)
day = '0' + day;
var year = arrDate.getFullYear();
$("#Departure").val(day + '-' + month + '-' + year);
}
}
this condition not related with the validation that i want this is to
set departureDate +1 after arrival date on change
if (arrivalDate >= departureDate)
this condition not related with the validation that i want this is to
set departureDate +1 after arrival date on change
if(arrivalDate < departureDate)
this condition i make it for this validation but didn't work
if (timeDiff > 1)
Instead of using the getDate() method to calculate the timeDiff, use getTime() and do a simple subtraction, followed by a millisecond-to-days refactoring.
Something like this:
var startDate = $("#Arrival").val().split("-");
var endDate = $("#Departure").val().split("-");
var arrivalDate = new Date(startDate[2], startDate[1] - 1, startDate[0]);
var departureDate = new Date(endDate[2], endDate[1] - 1, endDate[0]);
var timeDiff = Math.abs(departureDate.getTime() - arrivalDate.getTime());
var diffDays = Math.ceil(timeDiff / (1000 * 3600 * 24));
Additionally, while subtracting Date type values, the getTime() method becomes optional and a direct subtraction departureDate - arrivalDate can also be done.
If you're using datejs, creating a TimeSpan will help here.
var sync = function () {
var val1 = $("#Arrival").val();
var val2 = $("#Departure").val();
var startDate = Date.parseExact(val1, "ddMMMyy");
var endDate = Date.parseExact(val2, "ddMMMyy");
var diff = new TimeSpan(endDate - startDate);
var newEndDate = startDate.add(diff.days).days();
$("#Departure").val(newEndDate.toString("ddMMyyy"));
};
You could trigger this function to automatically fire by wiring up a change listener on the startDate input field. Just a thought.
Hope this helps.
To do this you need to remember either the arrival date before it was modified, or the number of days between arrival and departure dates. That way you can adjust the departure date by whatever amount the arrival date moved by.
You can store the "old" arrival date in lots of places, the defaultValue might be a good place. So when arrival date is updated, compare the new arrival date to the old one, set the old do the new one and adjust the departure date accordingly, e.g.
// Some helper functions
function parseDMY(s) {
var b = s.split(/\D/);
var d = new Date(b[2], --b[1], b[0]);
return d && d.getMonth() == b[1]? d : new Date(NaN);
}
function formatDate(date) {
if (isNaN(date)) return date.toString();
function z(n){return (n<10?'0':'')+n}
return z(date.getDate()) + '-' +
z(date.getMonth()+1) + '-' +
date.getFullYear();
}
function arrivalChange() {
// Check value entered is valid, if so,
// make sure formatted correctly
var arrDate = parseDMY(this.value);
// Deal with invalid input
if (isNaN(arrDate)) {
this.value = "Invalid date";
this.focus();
return;
}
// Tidy formatting
this.value = formatDate(arrDate);
var daysDiff, depDate;
var depEl = this.form.departureDate;
// Get number of days shifted and move departure date accordingly
daysDiff = Math.round((arrDate - parseDMY(this.defaultValue)) / 8.64e7);
this.defaultValue = this.value;
depDate = parseDMY(this.form.departureDate.defaultValue);
depDate.setDate(depDate.getDate() + daysDiff);
this.form.departureDate.value = formatDate(depDate);
this.form.departureDate.defaultValue = formatDate(depDate);
}
function departureChange(){
// Check value entered is valid, if so,
// make sure formatted correctly
var depDate = parseDMY(this.value);
if (isNaN(depDate)) {
this.value = 'Invalid date';
this.focus();
} else {
this.value = formatDate(depDate);
this.defaultValue = formatDate(depDate);
}
}
// Set dates in inputs, attach listeners
window.onload = function() {
var form = document.forms[0];
var now = new Date();
form.arrivalDate.value = formatDate(now);
form.arrivalDate.defaultValue = form.arrivalDate.value;
now.setDate(now.getDate() + 1);
form.departureDate.value = formatDate(now);
form.departureDate.defaultValue = form.departureDate.value;
form.arrivalDate.addEventListener('change', arrivalChange, false);
form.departureDate.addEventListener('change', departureChange, false);
};
<form onsubmit="return false;">
Arrival date (dd-mm-yyy): <input name="arrivalDate"><br>
Departure date (dd-mm-yyy): <input name="departureDate"><br>
<input type="reset">
</form>
If the user enters an invalid date at any time, pressing reset should get back the previous values.

Javascript increment and decrement YYYY-MM-DD by 1 day

I got this from another stack question
incr_date(date_str){
let parts = date_str.split("-");
let dt = new Date(
parseInt(parts[0], 10), // year
parseInt(parts[1], 10) - 1, // month (starts with 0)
parseInt(parts[2], 10) // date
);
dt.setDate(dt.getDate() + 1);
parts[0] = "" + dt.getFullYear();
parts[1] = "" + (dt.getMonth() + 1);
if (parts[1].length < 2) {
parts[1] = "0" + parts[1];
}
parts[2] = "" + dt.getDate();
if (parts[2].length < 2) {
parts[2] = "0" + parts[2];
}
return parts.join("-");
}
It works but how can I convert this function to decrement the date instead of increment?
I'm doing this on a react native component so I dont want to import any javascript libraries like moment.js
function dateAdd(dte){
var date = new Date(dte);
date.setDate(date.getDate() + 1);
console.log("add one day= "+date)
}
function datesub(dte){
var date = new Date(dte);
date.setDate(date.getDate() - 1);
console.log("minus one day = "+ date)
}
dateAdd("01-01-2017")
datesub("01-01-2017")
I'd convert the string to Javascript understandable format, increment a day and convert it back to user understandable format. I'm using the flag(Boolean) to determine weather to Increment the date and vice versa.
var convertDate = function(dt, flag) {
var dateArr = dt.split('-');
var tempDate = new Date();
var mm = dateArr[1] - 1; //Javascript considers 0 as Jan
tempDate.setFullYear(dateArr[0]);
tempDate.setMonth(mm);
tempDate.setDate(dateArr[2]);
if (flag) {
tempDate.setDate(tempDate.getDate(dateArr[2]) + 1);//Add's one day
} else {
tempDate.setDate(tempDate.getDate(dateArr[2]) - 1);//Sub's one day
}
var userFriendlyMonth = (Number(tempDate.getMonth()) + 1); //user considers 1 as Jan
return tempDate.getFullYear() + '-' + userFriendlyMonth + '-' + tempDate.getDate();
}
document.getElementById("increment").innerHTML = convertDate('2018-11-30', true);
document.getElementById("decrement").innerHTML = convertDate('2018-11-30', false);
<div>Increment: <span id="increment"></span></div>
<div>Decrement: <span id="decrement"></span></div>

How to get first Monday of Month and Week in fullcalendar control

I have one case related to fullCalendar control. I am showing Days from Mon-Fri and there is Custom Button added named as Add new Appointment. When user clicks on this button we need to show First Monday date for Month view and if it is Week view we need to show 1st date(Monday) of that week. '
I have done this way till now it's working for IST time Zone but my client is CST/EST and it takes previous day. Example- on Month view if i go to Feb and click on Add new it should 02-02-2016 but it's taking 01-31-2015.
function processDateTimeForNewCalendar() {
debugger;
var mondayForWeek = common.getMondayForCurrentWeek(new Date());
var dateHeader = $('div.fc-center h2').text();
var view = $('#calendar').fullCalendar('getView');
var date, sTime, eTime;
var currentDate = new Date();
if (view.name === 'month') {
debugger;
var currentMonth = dateHeader.split(" ")[0];
var currentYear = dateHeader.split(" ")[1];
var monthInNo = common.getMonthNumberByMonthName(currentMonth);
var temp = currentDate.getDate() + "-" + currentMonth + "-" + currentYear + " " + currentDate.getHours() + ":" + currentDate.getMinutes()
var tempDate = new Date(temp);
var mondayForWeek = common.getMondayForCurrentWeek(tempDate);
if ((currentDate.getMonth() + 1) === monthInNo)
date = new Date(currentDate.getDate() + "-" + currentMonth + "-" + currentYear + " " + currentDate.getHours() + ":" + currentDate.getMinutes());
if ((currentDate.getMonth() + 1) < monthInNo || (currentDate.getMonth() + 1) > monthInNo)
date = new Date(view.intervalStart);
sTime = moment(date).format("hh:mm A");
eTime = moment(date).add(30, 'minutes').format("hh:mm A");
}
if (view.name === 'agendaWeek' || view.name === 'agendaDay') {
date = new Date(view.start);
date = moment(date).format("MM/DD/YYYY");
sTime = moment(currentDate).format("hh:mm A");
eTime = moment(currentDate).add(30, 'minutes').format("hh:mm A");
}
$(CALENDAR.ApptStartDateById).val(moment(date).format("MM/DD/YYYY"));
$(CALENDAR.ApptEndDateById).val(moment(date).format("MM/DD/YYYY"));
$(CALENDAR.ApptStartTime).timepicker("setTime", sTime);
$(CALENDAR.ApptEndTime).timepicker("setTime", eTime);
$(CALENDAR.Duration).val(calculateDuration());
$(CALENDAR.ApptStartDateById).datepicker("update", date).datepicker('fill');
$(CALENDAR.ApptEndDateById).datepicker("update", date).datepicker('fill');
}
Please help me fix this.
Thanks,
Amod
You can use $('calendar selector').fullCalendar('getView').start to get the starting date of your current view;
I have done it in other way by finding the first Day of the Month and checks if it is sunday. If it is then add +1 day. Check the code below-
function getFirstDayOfMonth(d) {
d.setMonth(d.getMonth(), 1);
// if sunday add +1 day
if (d.getDay() === 0)
d.setDate(d.getDate() + 1, 1);
return d;
}
Hope, this is the alternate solution for finding first day of month using fullCalendar.

Not getting date format using javascript

I want to get all dates in between 2 dates. So here I have mentioned statdate is date and end date is weekdate. In between 2 dates I want all dates.
Actully I am getting all dates But Not proper Format ,what i want in this format DD/MM/YY.
Now I am Getting in default Format (Sat Jun 09 2007 17:46:21)
$(document).ready(function () {
$("#day").click(function () {
startJsonSession();
return false;
});
function startJsonSession() {
var inputdate = $('#inputdate').val();
//alert("Input Date!!!" + inputdate );
var d = new Date(inputdate);
var nowMS = d.getTime(); // get # milliseconds for today
//alert(nowMS);
var week = 1000 * 60 * 60 * 24 * 7; // milliseconds in one week
//alert(week);
var oneWeekFromNow = new Date(nowMS + week);
//alert("oneWeekFromNow!!!" + oneWeekFromNow);
var fromdate = d.getDate();
var month = d.getMonth() + 1;
var year = d.getFullYear();
if (fromdate < 10) {
fromdate = "0" + fromdate;
}
if (month < 10) {
month = "0" + month;
}
//var date = fromdate + "/" + month + "/" + year;
var date = year + "/" + month + "/" + fromdate;
alert("InputDate!!!!" + date);
//var weekdate=oneWeekFromNow.getDate() + "/" + month + "/" + year;
var weekdate = year + "/" + month + "/" + oneWeekFromNow.getDate();
alert("weekdate!!!" + weekdate);
var tomorrow = new Date(d.getTime() + (24 * 60 * 60 * 1000));
var tomorrowdate = tomorrow.getDate();
var month1 = tomorrow.getMonth() + 1;
var year1 = tomorrow.getFullYear();
if (tomorrowdate < 10) {
tomorrowdate = "0" + tomorrowdate;
}
if (month1 < 10) {
month1 = "0" + month1;
}
//var nextday = tomorrowdate + "/" + month1 + "/" + year1;
var nextday = year1 + "/" + month1 + "/" + tomorrowdate;
alert("tomorrow!!!!" + nextday);
var d1 = new Date(date);
alert("D1!!!!!" + d1.);
var d2 = new Date(weekdate);
var aDates = [];
do {
aDates.push(d1.toString());
d1.setDate(d1.getDate() + 1);
}
while (d1 <= d2);
alert("Dates!!!" + aDates);
//alert(aDates.join("\n"));
}
});
You can do it in this way
$("#getDate").click(function () {
var start = $("#startdate").datepicker("getDate"),
end = $("#enddate").datepicker("getDate");
currentDate = new Date(start),
between = [];
while (currentDate < end) {
between.push(new Date(currentDate));
currentDate.setDate(currentDate.getDate() + 1);
}
for (var i = 0; i < between.length; i++) {
var date = $.datepicker.formatDate('dd/mm/yy', new Date(between[i]));
between[i] = date;
}
console.log(between)
})
Here 'between' is the array which contains all your required Date
SEE DEMO HERE
alert("Dates!!!" + aDates.getDate()+"/"+ (aDates.getMonth()+1)+"/"+ aDates.getFullYear());
You seem to want to get a array of date strings in d/m/y format given an input string in the same format. The following functions will do that.
// Parse a string in dmy format
// return a date object, NaN or undefined
function parseDMY(s) {
var b = s.match(/\d+/g);
if (b) {
return new Date(b[2], --b[1], b[0]);
}
}
// Given a date object, return a string in dd/mm/yyyy format
function formatDMY(date) {
function z(n){return (n<10? '0' : '') + n;}
return z(date.getDate()) + '/' + z(date.getMonth() + 1) + '/' + date.getFullYear();
}
function getWeekDates(s) {
var d = parseDMY(s);
var dates = [];
if (d) {
for (var i=0; i<7; i++) {
dates.push(formatDMY(d));
d.setDate(d.getDate() + 1);
}
return dates;
}
}
console.log(getWeekDates('7/7/2014').join());
// 07/07/2014,08/07/2014,09/07/2014,10/07/2014,11/07/2014,12/07/2014,13/07/2014
Note that adding 1 day to a date is preferred over adding milliseconds as it allows the Date object to take account of daylight saving changes that might be involved.

Categories