Dates changing when I change another date [duplicate] - javascript

This question already has answers here:
How do I correctly clone a JavaScript object?
(81 answers)
Changing date copied from an object [duplicate]
(3 answers)
Closed 2 years ago.
so I 'm having a strange bug here related to changing the month of a date object. here is the code.
let date = new Date();
let captions = [];
for (let i=0; i < 12; i++) {
let newDate = date;
newDate.setMonth(date.getMonth() - i);
let month = newDate.toLocaleString('default', { month: 'short' });
let year = newDate.getFullYear();
captions.push({month, year});
}
The thing is value of date variable is changing every loop. I can understand why.
Anyone?

Your issue is with this assignment: let newDate = date;
What happens is that now newDate is a reference to your original date variable.
As Lennholm suggested in his comment below:
"it's not a reference to the original variable but to the same object
(in memory) that the original variable also references. The two
variables are independent of each other."
To avoid that change it to this: let newDate = new Date(date);
Check this stackblitz.

Related

getTime method is not working in javascript [duplicate]

This question already has answers here:
Convert date to another timezone in JavaScript
(34 answers)
Closed 1 year ago.
I have a little javascript file which I need to get the time of different timezone. I am only able to get the date but not the time.
let today = new Date();
let time = today.getTime();
let us = new Intl.DateTimeFormat('en-US').format(time);
let sv = new Intl.DateTimeFormat('sv').format(time);
console.log(us)
console.log(sv)
result in the console
2/25/2021
2021-02-25
i was able to solve the problem by using a javascript method called split whic was able to get me only the time part of the result.
const str3 = new Date().toLocaleString('en-US', { timeZone: 'Asia/Jakarta' });
ch_time = str3.split(" ")[1];
console.log(ch_time)
You can specify the date and time format using the "timeStyle" and "dateStyle" options. These can be full, long, medium, and short.
let us = Intl.DateTimeFormat('en-US', { dateStyle: 'full', timeStyle: 'long' }).format(time));
The above code will produce:
"Weekday, day Month Year at hh:mm:ss GMT+X"

Comparing datetime to the current date javascript [duplicate]

This question already has answers here:
How to know date is today?
(3 answers)
Closed 2 years ago.
I have an object that contains a property of date with a value of 2020-09-02T00:00:00.000Z. I want this value to be compared if it is within the current date or not, meaning if it is within 2020-09-01 00:00:00.00 to 2020-09-01 11:59:59.99. How will I be able to achieve this? This is my initial line of codes. Hope you can help me. Cheers!
for(let a = 0, c = arr3.length; a < c; a++){
let olddate = arr3[a].scheduled_time_start.valueOf();
}
You can compare native Date objects with comparison (<, <=, >, >=) operators.
const isDateInbetween = (date, startDate, endDate) =>
date > startDate && date < endDate;
const pastDate = new Date('2020-09-01T00:00:00.000Z');
const futureDate = new Date('2020-09-01T11:59:59.999Z');
const currDate = new Date('2020-09-02T00:00:00.000Z');
console.log(isDateInbetween(currDate, pastDate, futureDate)); // false

Increment Month in JavaScript removes the DATE format using setMonth() [duplicate]

This question already has answers here:
Why does Date.parse give incorrect results?
(11 answers)
Closed 4 years ago.
Below is my JavaScript Code to try and create a Maximum date where the user can't book past so many months into the future:
var x= 12;
var arriveDate = "28/11/2018"
var currentDate = new Date();
var a_date = new Date(arriveDate);
var max_month = currentDate.setMonth(currentDate.getMonth()+ x);
if (arriveDate === ""){
$("#arrive_date_error").html("Please don't leave this field blank");
}
else if (a_date < currentDate){
console.log("Please don't select a date in the past")
}
else if (a_date > max_month){
console.log("date in future")
}
The last else if never seems to work no matter what month/day/year I try. I decided to use console.log(max_month) to see what month it was creating and it returned:
1574953488195
Rather than the correct format:
Thu Nov 28 2019 15:04:48 GMT+0000
What am I doing wrong and why is it changing the format when I try to change the month of the date object?
setMonth mutates the currentDate, it does not return a new date. You probably want to clone the date and set the months of that cloned one:
var max_month = new Date(+currentDate);
max_month.setMonth(max_month.getMonth() + x);

Javascript date shows a day before [duplicate]

This question already has answers here:
Why does Date.parse give incorrect results?
(11 answers)
Where can I find documentation on formatting a date in JavaScript?
(39 answers)
Closed 4 years ago.
I'm using mydatepicker in my Angular application. When user clicks a specific date I'm getting the selected date. But I want to have a date format like this.
20180320
or
2018-03-20
So what I did was to convert as follows.
onDateChange(event) {
this.selectDate = event.jsdate.toISOString().slice(0,10)
}
This helps me to get my format. But it shows a day before. That means , if a user selects 2018-03-20 from calendar my selectDate = 2018-03-19
I can do that using moment , but for this project I'm not using for some reasons.Could someone help me to correct this?
Try this to account for timezone
onDateChange(event){
var localDate = new Date(event.jsdate.getTime() - event.jsdate.getTimezoneOffset() * 60000);
this.selectDate = localDate.toISOString().slice(0,10);
}
toISOString is always in UTC+0 time. If you console.log it, you should see a Z on the end. That means GMT.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString
Just try this with prototype function
Date.prototype.getDDMMYYYY = function () {
var date = JSON.stringify(this.getDate()).length == 1 ? ("0" + this.getDate()) : this.getDate();
var month = JSON.stringify(this.getMonth()).length == 1 ? ("0" + this.getMonth()) : this.getMonth();
var year = this.getFullYear();
return year+"-"+month+"-"+date;
}
and Just replace this code
onDateChange(event){
this.selectDate = event.jsdate.getDDMMYYYY()
}

Generate random date within one year and assign to var [duplicate]

This question already has answers here:
Elegant method to generate array of random dates within two dates
(7 answers)
Closed 7 years ago.
How would I code this:
var randomDate = some random date between 01/01/2015 and 12/31/2015 formatted in mm/dd/yyyy;
alert(randomDate);
Try this you need jquery UI as well with this solution:
function randomDate(start, end) {
var date = new Date(+start + Math.random() * (end - start));
return date;
}
var date1 = new Date(2013,09,01);
var date2 = new Date(2013,09,20);
alert($.datepicker.formatDate("mm/dd/yy",randomDate(date1, date2)));
Updated JS fiddle:
http://jsfiddle.net/f5q91cxn/2/

Categories