JS: Date manipulation [duplicate] - javascript

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);
}

Related

Value of variable is getting changed automatically [duplicate]

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;
}

How to sum date with minute with javascipt [duplicate]

This question already has answers here:
How to add 30 minutes to a JavaScript Date object?
(29 answers)
Closed 7 months ago.
I have a date:
start : 2022-07-13 08:22:22
process : 50 minute
And I want to output sum total
total = 2022-07-13 09:12:22 // total = start + process minute
I'm using javascript for sum
function myFunction() {
var datestart = $("#start").val();
var process = $("#process").val();
total = datestart + process;
alert(total);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
const dateStr = '2022-07-13 08:22:22';
const date = new Date(dateStr);
const addMinutes = (d, minutes) => {
const _date = new Date(d);
_date.setMinutes(_date.getMinutes() + minutes);
return _date;
}
const format = (date) => {
return date.toISOString().replace("T"," ").substring(0, 19);
}
console.log('original time', format(date));
console.log('add 30 minutes to the original time', format(addMinutes(date, 30)));
console.log('add 50 minutes to the original time', format(addMinutes(date, 50)));

In JavaScript (Node.JS), how do I parse a value like '202111031437' to output date? [duplicate]

This question already has answers here:
How to parse a date in format "YYYYmmdd" in JavaScript?
(6 answers)
Closed 1 year ago.
Have previously tried to use Date.parse() but 'undefined' is returned.
let datetime = '202111031437';
let parse = Date.parse(datetime);
console.log(parse);
Solved the query:
const dateParser = (dateString) => {
const year = dateString.substring(0, 4);
const month = dateString.substring(4, 6);
const day = dateString.substring(6, 8);
const hour = dateString.substring(8, 10);
const min = dateString.substring(10, 12);
const dateConcat = year + "-" + month + "-" + day + " " + hour + ":" + min;
const dateTime = new Date(dateConcat);
return dateTime;
}
let datetime = '202111031437';
let year = datetime.substring(0, 4);
let month = datetime.substring(4, 6);
let day = datetime.substring(6, 8);
let hour = datetime.substring(8, 10);
let minute = datetime.substring(10, 12);
console.log(new Date(year, month, day, hour, minute));

JS function enters an infinite loop when I have more values in holidays array [duplicate]

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.

JavaScript - difference between two time strings [duplicate]

This question already has answers here:
Check time difference in Javascript
(19 answers)
Closed 5 years ago.
I need to compare two different datetime strings (formed: YYYY-MM-DD'T'HH:mm).
Here are the datetime strings:
var a = ("2017-05-02T10:45");
var b = ("2017-05-02T12:15");
I've sliced the dates out of them so I only need the time (formed: HH:mm).
var now = a.slice(11, 16);
var then = b.slice(11, 16);
// now = 10:45
// then = 12:15
Is there any way I could get the difference between these two times?
Result should look like this:
1 hour 30 minutes
Also if the dates are different is there any easy solution to get the date difference too?
Use javascript Date:
var a = ("2017-05-02T10:45");
var b = ("2017-05-02T12:15");
var milliseconds = ((new Date(a)) - (new Date(b)));
var minutes = milliseconds / (60000);
This should get you started:
d1 = new Date(Date.parse("2017-05-02T10:45"));
d2 = new Date(Date.parse("2017-05-02T12:15"));
var getDuration = function(d1, d2) {
d3 = new Date(d2 - d1);
d0 = new Date(0);
return {
getHours: function(){
return d3.getHours() - d0.getHours();
},
getMinutes: function(){
return d3.getMinutes() - d0.getMinutes();
},
getMilliseconds: function() {
return d3.getMilliseconds() - d0.getMilliseconds();
},
toString: function(){
return this.getHours() + ":" +
this.getMinutes() + ":" +
this.getMilliseconds();
},
};
}
diff = getDuration(d1, d2);
console.log(diff.toString());
or use momentjs because, 1. it is well tested and bugs are tracked. 2. Coding from scratch is a fun learning experience but if you are in a corporate enviroment, coding from scratch will waste time (and thus money).
i have a lib to make this simple:
wiki:https://github.com/jiangbai333/Common-tools/wiki/format
code:https://github.com/jiangbai333/Common-tools/blob/dev/string/string.js
include string.js in your file, Then:
var temp = "short-stamp".format(+new Date("2017-05-02T12:15")) - "short-stamp".format(+new Date("2017-05-02T10:45"));
console.log(parseInt(temp / 3600), "hour", parseInt(temp % 3600 / 60), "minutes")

Categories

Resources