Generate dates between 2 ranges (js) - javascript

I'm newbie in javascript and need a little help.
How to generate all dates between dateA to dateB.
For example:
dateA = 07/01/2013
dateB = 07/01/2014
Wanted result:
07/01/2013, 07/02/2013, 07/03/2013, 07/04/2013...and so on
Any help would be greatly appreciated :)

Javascript doesn't have the simplest library for dealing with dates. Particularly when it comes to adding dates. One common method is to convert the date object into its representation in seconds using getTime() then to add the required number of seconds and pass that result into the new Date method. Something like this:
var dateA = new Date(2014,6,1,0,0,0);
var dateB = new Date(2014,6,4,0,0,0);
for(var myDate = dateA; myDate <= dateB; myDate = new Date(myDate.getTime() + 1000 * 60 * 60 * 24))
{
var formatedDate = myDate.getMonth()+1;
formatedDate += "/" + myDate.getDate() + "/" + myDate.getFullYear();
console.log(formatedDate);
}
Also remember that in javascript months are zero indexed (0-11).

Related

Calculate the difference between two dates and give the result in hh:mm format

date1=2023-01-02T12:22:00
date2=2023-01-03T22:15:00
How could I found the time difference?
function secondsToHMS(secs) {
function z(n){return (n<10?'0':'') + n;}
var sign = secs < 0 ? '-' : '';
secs = Math.abs(secs);
return sign + z(secs/3600 |0) + ':' + z((secs%3600) / 60 |0);
}
var d1 = new Date('2023-01-03T22:15:00');
var d2 = new Date('2023-01-02T12:22:00');
//console.log( secondsToHMS((d1 - d2) / 1000)); // 33:53
You can refer to the answer here: https://stackoverflow.com/a/12193371/9067107
The steps are firstly converting the UTC time via new Date() and calculate the different by date1 - date2 and get the Hours / Minutes different.
Lets assume you want to have HH:mm format in string
let date1 = new Date('2023-01-02T12:22:00')
let date2 = new Date('2023-01-03T22:15:00')
let diff = new Date(date2 - date1)
let diffInHoursMinutes = `${diff.getHours()}:${diff.getMinutes()}`

take a date string, add a class to span if expiration date is less than 2 weeks from now

i've been stuck on this problem for a while now and I am ready to pull my hair out :). I have to add a class to a span if a campaign date is expiring in 2 weeks or less. The date retrieved is a string in the following format
07/26/2017
when I run this function, I am passing the datestring as an argument since the method will be attached to the var which holds the string. But for whatever reason this logic isn't working. Am I totally screwing this up? It's failing silently somewhere. Thank you. I know it should be easy but I am caught in a loop.
campMethods.EndDateAlert = function (dateString) {
var currentDate = new Date ();
var twoWeeks = new Date ();
twoWeeks.setDate(currentDate.getDate() + 14)
var $EndDateSpan = $('.campaign-end-date');
if (dateString <= twoWeeks) {
$EndDateSpan.addClass('red');
}
return dateString;
};
You can do that with some Math. The key is, 2 weeks = 14 days.
Here is Pure Javascript example for you:
var date = "07/26/2017".split("/");
var formatedDate = (date[2] + '' + date[0] + '' + date[1]);
var currentDate = new Date();
var today = currentDate.getFullYear() +''+ ("0" + (currentDate.getMonth() + 1)).slice(-2)+''+("0" + currentDate.getDate()).slice(-2);
var compareDay = formatedDate - today;
if(compareDay < 14){// 14 day = 2 week
// do something for less than 2 weeks
console.log('Less than 2 weeks will be expired');
} else {
// also can do something
console.log('more than 2 weeks will be expired.');
}
Javascript Date Reference
Try comparing milliseconds of the dates.
We know that there are 1000 * 60 * 60 * 24 * 14 = 1209600000 milliseconds in two weeks, knowing this we can add 1209600000ms to the current date and compare this to the milliseconds of the due date.
let dueDate = new Date('07/26/2017');
if(Date.now() + 1209600000 > dueDate.getMilliseconds()){
//do stuff
}

Decrement the date by one day using javascript for loop?

$(document).ready(function() {
var date = new Date();
var data_new = [];var url ='http://www.domain.com /kjdshlka/api.php?date=2014-07-15';
$.getJSON(url,function(result) {
var elt = [date,result.requests];data_new.push(elt);console.log(data_new);
});
});
I am struggling to decrement the date by one day using javascript for loop.Here is my code,from the url im getting some requests.like if i decrease the date by one day other requests will come .Now i need this process for 7days using javascript for loop.Can anybody please tel me how to do ?
var date = new Date(); // Date you want, here I got the current date and time
date.setDate(date.getDate()-1);
getDate() will give you the date, then reduce it by 1 and using setDate() you can replace date again.
var today = new Date();
var yesterday = new Date(today.getTime() - (24 * 60 * 60 * 1000)); //(hours * minutes * seconds * milliseconds)
console.log(yesterday);
var now = new Date();
console.log(now);
var yesterday = new Date(now - 86400000);
console.log(yesterday);
/* In a Decrement Loop*/
for(var i=100;i>0;i--){
console.log(new Date(now - i*86400000));
}

Get time difference in javascript ISO format

I have a datetime in ISO format i.e.
2012-06-26T01:00:44Z
I want to get the time difference from current time. How can I achieve this using javascript or javascript library Date.js or jquery
This will give you the difference in milliseconds, you can then format it as you want
var diff = new Date("2012-06-26T01:00:44Z") - new Date();
Try this:
var someDate = new Date("2012-06-26T01:00:44Z");
var now = new Date();
var one_day = 1000 * 60 * 60 * 24;
var diff = Math.ceil((someDate.getTime()-now .getTime())/(one_day))
alert(diff)
Example fiddle
You can obviously amend the one_day variable to get the difference in the unit you require.
I would suggest converting ISO format to something that works cross browser.
Try this,
var d = "2012-06-26T01:00:44Z";
var someDate = new Date(d.replace(/-/g,'/').replace('T',' ').replace('Z',''));
alert(someDate - new Date());
Edit:
I guess, you need pretty time
Try this awesome code
Edit 2:
You needed reverse, so try this instead
var old_date = new Date();
alert('Old date: ' + old_date.toGMTString())
var new_date = new Date(old_date.setMinutes(old_date.getMinutes() - 5));
alert('Date 5 minutes before: ' + new_date.toGMTString());
If you need timestamp,
alert(new_date.getTime());
in order to format date you can use this function to get the desire format of the date and you can easily change the position of day , month and year.
function convertFormat(inputDate)
var date = new Date(inputDate);
var day = date.getDate();
var month = date.getMonth()+1;
var year = date.getFullYear();
var fullYear = year + '/' + month + '/' + day
return fullYear;

Javascript Date Plus 2 Weeks (14 days)

I use this to get the date:
var currentTime = new Date()
var month = currentTime.getMonth() + 1
var day = currentTime.getDate()
var year = currentTime.getFullYear()
alert(month + "/" + day + "/" + year);
How can I add 2 weeks ? So instead of showing 10/13/2011, to show 10/27/2011 etc
Here is the fiddle: http://jsfiddle.net/25wNa/
I want the one input to have +14 days and the other +21
Note: I'd like the format to be > 10/13/2011 <.
12096e5 is a magic number which is 14 days in milliseconds.
var fortnightAway = new Date(Date.now() + 12096e5);
jsFiddle.
var currentTime = new Date();
currentTime.setDate(currentTime.getDate()+14);
Try this:
currentTime.setDate(currentTime.getDate()+14);
have made a fidle for you http://jsfiddle.net/pramodpv/wfwuZ/
Date.prototype.AddDays = function(noOfDays) {
this.setTime(this.getTime() + (noOfDays * (1000 * 60 * 60 * 24)));
return this;
}
Date.prototype.toString = function() {
return this.getMonth() + "/" + this.getDate() + "/" + this.getFullYear().toString().slice(2);
}
$(function() {
var currentTime = new Date();
alert(currentTime.AddDays(14));
});
12096e5 is a kind of magic number. Just 14 days in milliseconds in exponential notation.
This number is the result of 1000[ms] * 60[s] * 60[m] * 24[h] * 14[d] saved in exponential notation.
You can check it if you type Number('12096e5'). You will get 1209600000 [ms] which is exactly 2 weeks in milliseconds. The exponential notation makes it obscure.
You can write any other number in exponential notation to make the life of your fellow developers more interesting.
Date object has constructor which accepts milliseconds as an argument which argument can be in exponential notation.
var d = new Date(milliseconds);
var afterTwoWeeks = new Date(+new Date + 12096e5);
var afterTwoWeeks = new Date(+new Date + 1209600000);
Both are the same.
Well, JS times are in millisecond, so adding two weeks would be a case of working out what two weeks is in milliseconds, and adding that value.
var twoWeeks = 1000 * 60 * 60 * 24 * 14;
var twoWeeksTime = new Date(new Date().getTime() + twoWeeks);
var formattedDate = twoWeeksTime.getDate() + '/' + (twoWeeksTime.getMonth()+1) + '/' + twoWeeksTime.getYear();
Of course, this method falls down if you need to add months, since they're variable in length, but it's fine for adding days and weeks.
Alternatively, you use the DateJS library, which has functionality for exactly this kind of thing (plus loads more).
With DateJS, your code could look like this:
var twoWeeksTime = Date.today().add({ days: 14 });
var formattedDate = twoWeeks.TimetoString('dd/MM/yy');
Hope that helps.
Add or Subtract 2 weeks from current date
Below code example give output in YYYY-MM-DD format
If condition is added in the string to concatenate 0 with Month and Day which is less than 10.
var twoWeeks = 1000 * 60 * 60 * 24 * 14;
var twoWeeksTime = new Date(new Date().getTime() + twoWeeks); /* Add or Subtract here*/
var formattedDate = (twoWeeksTime.getFullYear()) + '-' +
((twoWeeksTime.getMonth()+1) < 10 ? "0"+(twoWeeksTime.getMonth()+1): (twoWeeksTime.getMonth()+1)) + '-' +
(twoWeeksTime.getDate() < 10 ? "0"+(twoWeeksTime.getDate()): (twoWeeksTime.getDate()));
document.body.innerHTML = formattedDate;
add the following prototype method
Date.prototype.addDays = function(days) {
this.setDate(this.getDate()+days);
}
and than its very simple to use,
currentTime.addDays(5);
If you are formatting a javascript date in a particular format, then I think you can have a look at this script http://blog.stevenlevithan.com/archives/date-time-format. All you would need to do after including the script is this new Date(+new Date + 1000* 60 * 60 * 24 * 14).format('dd/mm/yyyy') and you would get the output "27/10/2011"
The script is pretty small, just above 1KB minified. This is the link to a working fiddle http://jsfiddle.net/naryad/GufvT/

Categories

Resources