Javascript Date Plus 2 Weeks (14 days) - javascript

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/

Related

Timestamp calculated from the current time instead the source date

I want to add 30 days to a Date (including the timestamp), however, the timestamp is being calculated from the execution time of the script instead of the source data (loadStartDateTime).
I created a new date object and then set the date (purge_date = loadStartDateTime + 30days).
I saw an example doing some math with the dates, should I make the calculations of the timestamp separately?
PURGEDATE = (function (loadTime) {
var loadDate = new Date(loadTime);
var purge_date = new Date();
purge_date.setDate(loadDate.getDate()+30);
var month = purge_date.getMonth() + 1;
var mm = month < 10 ? "0" + month : month;
var day = purge_date.getDate();
var dd = day < 10 ? "0" + day : day;
var hours = purge_date.getHours() < 10 ? "0" + purge_date.getHours() : purge_date.getHours();
var minutes = purge_date.getMinutes() < 10 ? "0" + purge_date.getMinutes() : purge_date.getMinutes();
var seconds = purge_date.getSeconds() < 10 ? "0" + purge_date.getSeconds() : purge_date.getSeconds();
var time = hours + ":" + minutes + ":" + seconds;
var yyyy = purge_date.getFullYear();
return mm + "/" + dd + "/" + yyyy + time;
})(LoadStartDateTime)
The Result:
loadStartDateTime | PurgeDate
8/7/2018 5:55:45 PM | 09/06/2018 10:28:49
8/7/2018 5:58:10 PM | 09/06/2018 10:28:49
I saw an example doing some math with the dates, should I make the calculations of the timestamp separately?
Thank you~
After further investigation I realized that:
The Date object’s constructor is ISO 8601
When I use getDate() I do not provide the timezone explicitly.
This causes the timestamp to be 00:00:00 local time, so I should use getTime() method instead to get the timestamp. Since in JavaScript a timestamp is the number of milliseconds, a simple way to get it done is to send the timestamp value in the Date constructor. To calculate 30 days measured in timestamp:
30 * 24 * 60 * 60 * 1000
Finally, sum both values and send the result as a param in the constructor:
For example:
loadStartDateTime = new Date('8/7/2018 5:55:45 PM');
test_date = loadStartDateTime.getTime() + (30 * 24 * 60 * 60 * 1000);
test_date = new Date(test_date);
and then can continue with the Date Formatting.
I found the solution combining the answers from ISO 8601 date format - Add day with javascript and Add 30 days to date (mm/dd/yy). This guide "The Definitive Guide to DateTime Manipulation" helped to find out when I was wrong by understanding more about DateTime Manipulation.

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
}

How do I get the number of days for a duration where the number of hours exceeds 24 in google sheets?

I am using google sheets where there is a duration value of 69:41:00 where it's 69 hours, 41 minutes, 0 secs. There doesn't seem to be a function to convert this to days, hours and minutes so I did some searching and some had suggested a custom function. Not sure exactly how it works but made some changes from the original to fit what I needed. The code below:
/**
* Format Duration to Days,Hours,Minutes
*
* #param {duration} input value.
* #return Days,Hours,Minutes.
* #customfunction
*/
function FormatDuration(duration) {
// Retrieve the hours and minutes
var hrs = duration.getHours();
var days = Math.floor(hrs/24);
var hours = hrs % 24;
var mins = duration.getMinutes();
// Convert the result to a number to use in calculations
var result = days + 'd ' + hours + ' h '+ mins+' min';
return result;
}
The result should be 2d 21h 44 min but instead I got 0d 21 h 35 min. Am I doing something wrong here?
I was going to add, why don't you just use a custom format of
ʺd\d hh\h mm\mʺ ?
This works fine in Excel but not in GS because it uses a different base for dates so duration like 69:41:00 would be interpreted as 1/1/1900 21:41 and the days are not correct. So you would have to break it down into days (whole numbers) and hours+minutes (fractions of a day) like this
=text(int(A1),ʺ#0\d ʺ)&text(mod(A1,1),ʺHH\h MM\mʺ)
You can make it work in Google Scripts if you want to by adjusting the date - should work OK for durations up to 1 month.
The reason for adding 2 to the date is that a time like 03:21:00 (less than a day) is seen as a date - namely 30th December 1899 ! So I add 2 to it to make it 1st January 1900. However, now the day part of the date is 1 and I want it to be zero. So I have to subtract 1 from the day further down.
This strange behaviour is probably why you're advised to do it the other way and work in milliseconds, but I was just interested to see if there was a way of making the original code work.
/**
* Format Duration to Days,Hours,Minutes
*
* #param {duration} input value.
* #return Days,Hours,Minutes.
* #customfunction
*/
function FormatDuration(duration) {
// Add 2 days to the date
var date=new Date(duration.setDate(duration.getDate()+2));
Logger.log(date.getDate());
var hours = duration.getHours();
// Take 1 off the day part of the date
var days = date.getDate()-1;
var mins = duration.getMinutes();
// Convert the result to a number to use in calculations
var result = days + 'd ' + hours + ' h '+ mins+' min';
return result;
}
function(durations){
var timeArr = durations.split(':'); //["69","41","00"]
//your code
}
getHours is a method of object Date.
var t = new Date;
t.getHours();
How do you expect to get more than 24hours from a Date object? It is not the same as what you expect as Duration. Date is for points of time in calendar, so at most you'd get the 23:59:59 of any day. You can get date2 - date1 = milliseconds diff, and work on it, as following;
function FormatDuration(date1, date2) {
var milliseconds = date2 - date1;
var mins = Math.floor((milliseconds / (1000*60)) % 60);
var hours = Math.floor((milliseconds / (1000*60*60)) % 24);
var days = Math.floor(milliseconds / (1000*60*60*24));
var result = days + ' d ' + hours + ' h '+ mins + ' min';
console.log(result);
}
FormatDuration(new Date(2000, 5, 1, 5, 13, 0, 0),
new Date(2000, 5, 2, 15, 31, 0, 0))
You can find more details here

Check if time difference is less than 45 mins and run function - AngularJS

This is an easy thing to do in PHP with code like this;
if (strtotime($given_time) >= time()+300) echo "You are online";
But can't find anything on SO to do exactly this in javascript.
I want to check if the difference between a given time and the current time is less than 45mins
For instance
$scope.given_time = "14:10:00"
$scope.current_time = new Date();
I'm only concerned with the time part. I need to extract time part from new Date(); and then compare.
Then this should be true
How can I achieve this with Javascript:
if ($scope.given_time - $scope.current_time < 45 minutes) {
// do something
}
Javascript uses unix timestamps in milliseconds, so it is similar to the output of strtotime (which uses seconds).
var date = new Date();
Then you'll need to do the calculation from milliseconds. (Minutes * 60 * 1000)
You can also use date.parse() to parse a string to milliseconds, just like strtotime() in PHP does to seconds.
In full:
var date = new Date();
var last = new Date('Previous Date'); // or a previous millisecond timestamp
if ( ( date - last ) > ( 45 * 60 * 1000 ) ) {
// do something
}
You could use a static date to compare just time, this is exactly what strtotime does if you exclude the date:
var last = new Date('1/1/70 14:10:00');
var date = new Date('1/1/70 14:30:00');
However, this approach will fail if you're trying to compare time that cross over day boundaries.
Try this:
function checkTime(time) {
var date = new Date();
var date1 = new Date((date.getMonth() + 1) + "/" + date.getDate() + "/" + date.getFullYear() + " " + time);
var minutes = (date1.getTime() - date.getTime()) / (60 * 1000);
if (minutes > 45 || (minutes < 0 && minutes > -1395)) {
// greater than 45 is todays time is above 45 minutes
// less than 0 means the next available time will be tomorrow and the greater than -1395 means it will be more than 45 minutes from now into tomorrow
document.write(time + ': true<br />');
} else {
document.write(time + ': false<br />');
}
}
checkTime("14:10:00");
checkTime("16:30:00");
checkTime("17:10:00");
There's a JavaScript method called getMinutes(); you can use to get only the minutes and compare.
Your code should look something like:
var received_time = "14:10:00".split(':');
var minute = '';
if(received_time.length === 3) {
minute = parseInt(received_time[1], 10);
}
$scope.given_time = minute;
var the_time = new Date();
$scope.current_time = the_time.getMinutes();
And you now can do your thing:
if ($scope.given_time - $scope.current_time < 45 minutes) {
// do something
}
Using a library like moment.js you can simply diff the two times.
var $log = $("#log");
/* Difference between just times */
$log.append("Difference between times\n");
var givenTime = moment("14:10:00", "HH:mm:ss");
var minutesPassed = moment("14:30:00", "HH:mm:ss").diff(givenTime, "minutes");
$log.append("Minutes passed: " + minutesPassed + "\n");
if (minutesPassed < 45) {
$log.append(minutesPassed + " minutes have elapsed. Event Triggered." + "\n");
}
/* Better: Difference between times that have dates attached to them and cross a day boundary. */
$log.append("\n\nDifference between dates with times\n");
givenTime = moment("2015-12-03 23:33:00");
minutesPassed = moment("2015-12-04 00:14:00").diff(givenTime, "minutes");
$log.append("Minutes passed: " + minutesPassed + "\n");
if (minutesPassed < 45) {
$log.append(minutesPassed + " minutes have elapsed. Event Triggered." + "\n");
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://momentjs.com/downloads/moment.js"></script>
<p>Results:</p>
<hr>
<pre id="log"></pre>
<hr>
Caveat: If the given time is yesterday such as 11:30pm and the current time is 12:10am then you will get the wrong result. You'd want to use a date with the time if this type of thing is an issue for your use case.
The moment.js documentation
http://momentjs.com/docs/
Angular directive for moment documentation
https://github.com/urish/angular-moment/blob/master/README.md

Generate dates between 2 ranges (js)

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).

Categories

Resources