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

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/

Related

Dates changing when I change another date [duplicate]

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.

Add minutes to current time, JavaScript [duplicate]

This question already has answers here:
How to add 30 minutes to a JavaScript Date object?
(29 answers)
Closed 3 years ago.
I would like to add 20 minutes to the current date. While browsing the messages already posted on this subject, I recovered a piece of code but I can not adapt it. Can you help me ?
// get the current date & time
var dateObj = Date.now();
// I do not understand what these values ​​are
dateObj += 1000 * 60 * 60 * 24 * 3;
// create a new Date object, using the adjusted time
dateObj = new Date(dateObj);
Create a prototype function on Date Object if you want to use it in various places as it will reduce redundancy of code.
Date.prototype.add20minutes = function(){
return this.setMinutes(this.getMinutes() + 20);
}
Now, you can simply call
var d = new Date();
d.add20minutes();
Use this piece of code
var date = new Date();
date.setMinutes(date.getMinutes()+20);
Don't know if setMinutes with values > 60 is defined or it works by accident. You can do it this way:
var current_ms = new Date().getTime();
var in20min = new Date(current_ms + (1000*60*20))
JavaScript Date object has a method called setMinutes
let d = new Date()
d.setMinutes(d.getMinutes() + 20)
In javascript when working with dates I like to use moment:
https://momentjs.com/
So you can do this:
moment().add(20, 'minutes');
Use this code:
var date = new Date();
var min = parseInt(date.getMinutes()+20);
date.setMinutes(min);

Comparing the current date with a date received from an api response [duplicate]

This question already has answers here:
How to calculate date difference in JavaScript? [duplicate]
(24 answers)
Closed 4 years ago.
I want to compare the date I receive from an API to the current date and if it exceeds 14 days. The date I receive is in this format.
"date": "2018-08-07T14:17:24+02:00"
You can use the library date-fns to calculate this too. It has a smaller bundle size than Moment.
function exceedsDays(date, numberOfDays) {
var today = dateFns.startOfToday();
var diff = dateFns.differenceInDays(today, dateFns.parse(date));
return diff > numberOfDays;
}
var date = "2018-08-07T14:17:24+02:00";
var result = exceedsDays(date, 14);
console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/date-fns/1.29.0/date_fns.min.js"></script>
let dateFrom = new Date("2018-08-07T14:17:24+02:00").getTime();
let today = new Date().getTime();
let days14 = 1000 * 60 * 60 * 24 * 14;
if(today - dateFrom > days14){ }
If you go with momentjs you can do something like that. This will return you a boolean. You can reuse later this function to maybe check if more than 30 days etc. Just need to change the second argument. The first one is your date you want to check. By default moment() return now, this is the reason we don't need to create a date for now.
const oldDate = '2018-08-07T14:17:24+02:00';
function exceedNumOfDays(date, numOfDays) {
return moment().diff(new Date(date), 'days') > numOfDays;
}
exceedNumOfDays(oldDate, 14)
I put the code on codesandbox, you can see the console at the bottom left. https://codesandbox.io/s/oo967v83xq

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

Date Comparison Using Javascript [duplicate]

This question already has answers here:
Compare two dates with JavaScript
(44 answers)
Closed 8 years ago.
I have two date strings in DDMMYYYY format. say startdate="18/02/2013" and enddate ="26/02/2013".
How can I compare these dates. I want enddate to be greater than or equal to startdate
Thanks for Your Time.
I'm a fan of moment.js and consider it a core part of my toolkit whenever I have to deal with dates and times - especially when any form of parsing or formatting is involved.
You're free to do the parsing by hand and invoke the appropriate Date constructor manually, but consider the following which I consider simple and intuitive.
var startDate = moment.parse("18/02/2013", "DD/MM/YYYY");
var endDate = moment.parse("26/02/2013", "DD/MM/YYYY");
if (endDate.isAfter(startDate)) {
// was after ..
}
Does this solution suits your needs (demo : http://jsfiddle.net/wared/MdA3B/)?
var startdate = '18/02/2013';
var d1 = startdate.split('/');
d1 = new Date(d1.pop(), d1.pop() - 1, d1.pop());
var enddate = '26/02/2013';
var d2 = enddate.split('/');
d2 = new Date(d2.pop(), d2.pop() - 1, d2.pop());
if (d2 >= d1) {
// do something
}
Keep in mind that months begin with 0. MDN doc :
month : Integer value representing the month, beginning with 0 for January to 11 for December.
var d1 = Date.parse("18/02/2013");
var d2 = Date.parse("26/02/2013");
if (d1 > d2) {
alert ("do something");
}

Categories