This question already has answers here:
Javascript: Date object being changed [duplicate]
(1 answer)
Javascript date variable assignment
(9 answers)
How to clone a Date object?
(8 answers)
Closed last month.
I m new to JavaScript and facing a weird problem. after adding months to asset_purchase_date into a new variable, the value of asset_purchase_date is changing automatically.
function AssetValueToday(asset_purchase_date, asset_total_cost, asset_life_months, asset_sale_date, asset_value_ason) {
var return_value = 0;
if (asset_sale_date > asset_value_ason) {
if (asset_value_ason > asset_purchase_date) {
days_since_purchase = (Math.ceil(Math.abs(asset_value_ason - asset_purchase_date)) / (1000 * 60 * 60 * 24));
asset_end_date = addMonths(asset_purchase_date, asset_life_months);
// here do some stuff
}
return_value = asset_purchase_date;
} else {
return_value = 0;
}
return return_value;
}
function addMonths(date, months) {
date.setMonth(date.getMonth() + months);
return date;
}
Any help shall be highly appreciated.
This is because setMonth modifys the Date object (asset_purchase_date).
See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/setMonth
You have to create a new Date object, something like:
function addMonths(date, months) {
const newDate = new Date(date.getTime())
newDate.setMonth(newDate.getMonth() + months);
return newDate;
}
Related
This question already has answers here:
Modify a variable inside a function [duplicate]
(2 answers)
Variable vs Parameter Scope and Assignment Values
(4 answers)
Is JavaScript a pass-by-reference or pass-by-value language?
(33 answers)
Closed 3 years ago.
I want the check function to prepend "0" to hour if it is below 10.
var date = new Date();
var day = date.getDate();
var month = date.getMonth() + 1;
var year = date.getFullYear();
var hour = date.getHours();
var minutes = date.getMinutes();
function check(x) {
if (x < 10) {
x = '0' + x;
}
};
check(hour);
console.log(hour);
But when I check console.log(hour); it still returns the previous value. Why is this the case?
You need to return the value and you need to take the value from the function for an output or assignment.
function check(x) {
if (x < 10) {
return '0' + x;
}
return x;
}
In this case, I would change the name of the function to getFormatted and uzse a more abstract approach.
function getFormatted(value, size = 2) {
return value.toString().padStart(size, 0);
}
var date = new Date();
var day = date.getDate();
var month = date.getMonth() + 1;
var year = date.getFullYear();
var hour = date.getHours();
var minutes = date.getMinutes();
console.log(getFormatted(hour));
This question already has answers here:
Calculate previous working day excluding weekends and federal holidays in JavaScript
(2 answers)
Closed 3 years ago.
I have a working jsfiddle:
https://jsfiddle.net/x1z9mvLy/
function check_previous_business_date(date, timezone) {
const startDate = new Date(luxon.DateTime.fromISO(date).setZone(timezone));
const todayTimeStamp = +new Date(startDate); // Unix timestamp in milliseconds
const oneDayTimeStamp = 1000 * 60 * 60 * 24; // Milliseconds in a day
const diff = todayTimeStamp - oneDayTimeStamp;
const yesterdayDate = new Date(diff);
const yesterdayString = yesterdayDate.getFullYear()
+ '-' + (yesterdayDate.getMonth() + 1) + '-' + yesterdayDate.getDate();
for (startDate.setDate(startDate.getDate() - 1);
!startDate.getDay() || startDate.getDay() === 6 ||
federalHolidays.includes(startDate.toISOString().split('T')[0]) ||
federalHolidays.includes(yesterdayString);
startDate.setDate(startDate.getDate() - 1)
) {
}
return startDate.toISOString().split('T')[0];
}
const federalHolidays= [
'2019-05-27',
'2019-09-02',
'2019-10-14',
'2019-11-11'
];
console.log('Prev. day of 2019-05-28 is ',check_previous_business_date('2019-05-28T07:00:00.000Z', 'America/New_York'));
console.log('Prev. day of 2019-06-20 is ',check_previous_business_date('2019-06-20T07:00:00.000Z', 'America/New_York'));
console.log('Prev. day of 2019-06-24 is ',check_previous_business_date('2019-06-24T07:00:00.000Z', 'America/New_York'));
When I have just a few records in my federalHolidays array, it would work absolutely fine. But the problem is when the size of federalHolidays array increases, it enters an infinite loop.
Please checkout the fiddle.
This is your loop:
for (startDate.setDate(startDate.getDate() - 1);
!startDate.getDay() || startDate.getDay() === 6 ||
federalHolidays.includes(startDate.toISOString().split('T')[0]) ||
federalHolidays.includes(yesterdayString);
startDate.setDate(startDate.getDate() - 1)
) {
}
The problem is that yesterdayString never changes in the loop, so if it happens to be in federalHolidays, then you will have an infinite loop.
This question already has answers here:
How can I pad a value with leading zeros?
(76 answers)
Closed 4 years ago.
The time is returning incorrect format. I would like to return time in HH:MM format. The below code work doesn't work when the time has got zero in it, for example 14:00 14:03 and 14:10 returns in the following format 14:0, 14:3 or 14:1. Please shed some idea to resolve this.
function getTime() {
var time = new Date();
time.setHours(time.getHours()+1);
return time.getHours() +':'+time.getMinutes();
}
const getcurrTime = getTime();
.getHours() and .getMinutes() will always return an integer. You need to pad the integer:
function getTime() {
var time = new Date();
time.setHours(time.getHours()+1);
return time.getHours().toString().padStart(2, '0') +':'+time.getMinutes().toString().padStart(2, '0');
}
const getcurrTime = getTime();
console.log(getcurrTime);
For readability, I would most likely write:
function getTime() {
var time = new Date();
time.setHours(time.getHours() + 1);
var hours = time.getHours()
.toString()
.padStart(2, '0');
var minutes = time.getMinutes()
.toString()
.padStart(2, '0');
return hours + ":" + minutes;
}
var currentTime = getTime();
console.log(currentTime);
This question already has answers here:
How to add 30 minutes to a JavaScript Date object?
(29 answers)
Closed 4 years ago.
Trying to add hours to a date without success..
Variables and code I have tried:
const date = '2018-10-18';
const time = '20:35';
const timezn = 2;
let end = new Date(date);
const endTimeArray = _.split(time, ':', 2);
const endHours = parseInt(endTimeArray[0]);
const endMinutes = parseInt(endTimeArray[1]);
end.setHours(end.getHours() + endHours - timezn);
end.setMinutes(end.getMinutes() + endMinutes);
const result = end.toLocaleTimeString();
console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.js"></script>
Expected result:
"2018-10-18T20:35:00.000+02:00"
This question has already been asked, and answered, here (see user KIP)
However, for your example, the following should do.
let end = new Date(date);
let newEnd = addMinutes(end, 60);
function addMinutes(date, minutes) {
return new Date(date.getTime() + minutes*60000);
}
This question already has answers here:
How do I get the difference between two Dates in JavaScript?
(18 answers)
Closed 9 years ago.
I'm working on an assignment where I must use Javascript. In my application a user types a date into a form. Then I try to compare that date with the current date. The difference is the number of days they have to complete a task. However, I'm having a bit of trouble when it comes to the calculations. dueDate is a paramater for an object dynamically created.
function getFormData() {
var adate = document.getElementById("dueDate").value;
if (checkInputText(dueDate, "Please enter a date")) return;
...
}
function processDate(adate) {
var splitArray = adate.split("-");
var year = splitArray[0];
var month = splitArray[1] - 1;
var day = splitArray[2];
var date = new Date(year, month, day);
var dateParse = date.getTime();
return dateParse;
}
function compareDates(dueDate) { //dueDate is the value from the form
var cdate = new Date();
console.log("this is todays date" + " " + cdate); //shows correct date
var cdateparse = Date.parse(cdate);
var dueDateparse = Date.parse(dueDate);
var diff = dueDateparse - cdateparse;
var daysCal = diff / 1000 / 60 / 60 / 24;
var days = parseInt(daysCal); //where I'm having trouble
console.log(days);
if (days == 0) {
mymessage = " you have to do this task today";
}
try {
if (days < 0) {
mymessage = "this task is overdue by" + " " + -days + " " + "days";
throw new Error("you are overdue");
}
} catch (ex) {
alert(ex.message);
return;
}
if (days > 0) {
console.log("the difference is greater than 0");
mymessage = "you have" + " " + days + " " + "more days";
}
}
The issue happens when I put in the current date into the form. I've tried math.floor and math.round but the number is always rounded up and throws my message, saying that the task is overdue. Using parseInt has brought me closest to my desired outcome, but when I put in tomorrow's date it says that I am overdue. Any suggestions?
http://jsfiddle.net/sujesharukil/QspFj/
use
var days = Math.ceil(daysCal);
instead of parseInt.
You should beware of that new Date(year, month, day); creates a timestamp for 0:00 AM.
So everything that happens on that day, will already have a negative diff (> -1, though). So you should use Math.ceil instead of rounding. Or you set the deadline to 23:59:59 (i.e. just increase the day by 1).