Add minutes to current time, JavaScript [duplicate] - javascript

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

Related

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

Get millis when using new Date().toLocaleTimeString() [duplicate]

This question already has answers here:
Convert a Unix timestamp to time in JavaScript
(34 answers)
Closed 4 years ago.
I have this code:
v.d = new Date().toLocaleTimeString();
it yields something like this:
20:11:40
So this is the time of day to the second, without milliseconds.
My question is: is there a built in call that can show just the time with milliseconds?
I am looking for something like this (to the millisecond):
20:11:40.124
This works, but I am looking for something more compact if possible:
const d = new Date();
v.d = d.toLocaleTimeString() + `.${d.getMilliseconds()}`;
this yields:
20:17:30.744
note that to make this work well, you need to add this part:
Formatting milliseconds to always 3 digits for d.getMilliseconds() call
There’s to ISOString(). But stepping back a level, with that exception there’s no standard for formatting dates in js. So you can use toISOString or build up your own string with individual date functions.
I did find one issue with your original solution. When I perform it it yields hh:mm:ss PM.mil. I assume you want hh:mm:ss.mil Here is that solution written as a function so you can pass the date object in and get the proper format:
const d = new Date()
const getTimeWithMilliseconds = date => {
const t = d.toLocaleTimeString();
return `${t.substring(0,8)}.${date.getMilliseconds() + t.substring(8,11)}`;
}
console.log(getTimeWithMilliseconds(d));
Or if you want it in 24 hour format:
const d = new Date()
const getTimeWithMilliseconds = date => {
return `${date.toLocaleTimeString('it-US')}.${date.getMilliseconds()}`;
}
console.log(getTimeWithMilliseconds(d));
You can't depend on toLocaleTimeString returning a specific format as it's implementation dependent. It's much more reliable to build the format yourself, e.g.:
function getFormattedTime(date) {
var d = date || new Date();
var z = n => ('0'+n).slice(-2);
var zz = n => ('00'+n).slice(-3);
return `${z(d.getHours())}:${z(d.getMinutes())}:${z(d.getSeconds())}.${zz(d.getMilliseconds())}`;
}
console.log(getFormattedTime());
console.log(getFormattedTime(new Date(2018,1,1)));
console.log(getFormattedTime(new Date(2018,4,30,23,51,12,89)));
Also see Where can I find documentation on formatting a date in JavaScript?

Javascript get date 30 days ago [duplicate]

This question already has answers here:
How to subtract days from a plain Date?
(36 answers)
Closed 5 years ago.
I am trying to populate two date input fields, one with today's date and one with the date 30 days ago(last month).
I am getting an error in my console: priordate.getDate is not a function
Here is my code, not sure what I am doing wrong:
//today's date
var today = new Date();
var dd = today.getDate();
var mm = today.getMonth()+1;//January is 0, so always add + 1
var yyyy = today.getFullYear();
if(dd<10){dd='0'+dd};
if(mm<10){mm='0'+mm};
today = yyyy+'-'+mm+'-'+dd;
//30 days ago
var beforedate = new Date();
var priordate = new Date().setDate(beforedate.getDate()-30);
var dd2 = priordate.getDate();
var mm2 = priordate.getMonth()+1;//January is 0, so always add + 1
var yyyy2 = priordate.getFullYear();
if(dd2<10){dd2='0'+dd2};
if(mm2<10){mm2='0'+mm2};
var datefrommonthago = yyyy2+'-'+mm2+'-'+dd2;
// Set inputs with the date variables:
$("#fromdate").val(datefrommonthago);
$("#todate").val(today);
You'll instead want to use:
var priordate = new Date(new Date().setDate(beforedate.getDate()-30));
if you want it on one line. By using:
new Date().setDate(beforedate.getDate()-30);
you're returning the time since epoch (a number, not a date) and assigning it to priordate, but it's not a Date anymore and so does not have the getDate function.
This is because setDate() returns a number, not a Date Object.
In any I case I'd strongly recommend using momentjs or date-fns as the internal Date object in JavaScript is broken in all kind of ways. See this talk: https://www.youtube.com/watch?v=aVuor-VAWTI
Change this:
var priordate = new Date().setDate(beforedate.getDate()-30);
to this:
var priordate = new Date();
priordate.setDate(beforedate.getDate()-30);

Translate a native JS to Angularjs to calculate days between two dates?

I am having trouble trying to convert or translate a native js script to calculate number of days between two dates from two scopes ('work_start' and 'work_end') but did not have any success.
Here is the code, actually it works, but an alert is fired in the console.log and I am not achieving to solve this.
$scope.$watchGroup(['work_start', 'work_end'], function() {
var date1 = $scope.work_start;
var date2 = $scope.work_end;
// First we split the values to arrays date1[0] is the year, [1] the month and [2] the day
date1 = date1.split('-');
date2 = date2.split('-');
// Now we convert the array to a Date object, which has several helpful methods
date1 = new Date(date1[0], date1[1], date1[2]);
date2 = new Date(date2[0], date2[1], date2[2]);
// We use the getTime() method and get the unixtime (in milliseconds, but we want seconds, therefore we divide it through 1000)
date1_unixtime = parseInt(date1.getTime() / 1000);
date2_unixtime = parseInt(date2.getTime() / 1000);
// This is the calculated difference in seconds
var timeDifference = date2_unixtime - date1_unixtime;
// in Hours
var timeDifferenceInHours = timeDifference / 60 / 60;
// and finaly, in days :)
var timeDifferenceInDays = timeDifferenceInHours / 24;
// alert(timeDifferenceInDays);
$scope.total_days = timeDifferenceInDays;
});
And this is the alert I am receiving:
angular.js:13283 TypeError: Cannot read property 'split' of null
at app.js:3997
at c (angular.js:16419)
at m.$eval (angular.js:16884)
at m.$digest (angular.js:16700)
at m.$apply (angular.js:16992)
at g (angular.js:11313)
at y (angular.js:11511)
at XMLHttpRequest.t.onload (angular.js:11452)(anonymous function) # angular.js:13283(anonymous function) # angular.js:9996m.$digest # angular.js:16702m.$apply # angular.js:16992g # angular.js:11313y # angular.js:11511t.onload # angular.js:11452
I changed some things but this is the far I can get. Any help will be welcome
Cannot read property 'split' of null
This means you're trying to use the split function on something that is not a String. So where are you using the split function?
date1 = date1.split('-');
date2 = date2.split('-');
So where are date1/2 defined?
var date1 = $scope.work_start;
var date2 = $scope.work_end;
So where are $scope.work_start/end defined? Not sure, but probably in html. To simply fix this issue, do something like this:
if(date1 === null || date2 === null){
alert("no dates given")
} else {
date1 = date1.split('-');
date2 = date2.split('-');
... // rest of your code
}
Updating this section based on the discussion below...
Dates can be a pain in JS. A newly initialized date object is simply the number of milliseconds since January 1st, 1970 (UTC). If you're going to play with dates and times, look into a js library that makes Dates easier to work with like Moment or Sugar.
$watchGroup watches those two dates and runs the 'days between' functionality if either changes. This is fine, however you must compensate for a range of issues, such as
the user changes work_start before work_end, and work_start is after work_end
the user enters a date that is not in the correct format
and a bunch of other stuff that can come up. You might want to think about incorporating a button to allow the user to update the dates after they're finished editing both. This will also allow your form to error-check the input, and not allow a submission if it's not in the correct format.
HTML
<div ng-controller="workCont">
<input ng-model="$scope.work_start"></input>
<input ng-model="$scope.work_end"></input>
<button ng-click="$scope.getDaysBetween()">Get Days Between</button>
<p>Days Between: {{$scope.daysBetween}}</p>
</div>
JS
var workApp = angular.module('workApp', []);
workApp.controller('workCont', function workCont($scope) {
$scope.work_start = new Date();
$scope.work_end = new Date();
$scope.daysBetween = 0;
$scope.getDaysBetween = function(){
var date1 = $scope.work_start
var date2 = $scope.work_end
var timeDiff = Math.abs(date2.getTime() - date1.getTime());
var diffDays = Math.ceil(timeDiff / (1000 * 3600 * 24));
$scope.daysBetween = diffDays
}
});
Thanks to "Get difference between 2 dates in javascript?" for the getDaysBetween logic.

Add two months on start date in CRM using Javascript

I have task to make expiry date by adding two months on start date.
I have found this code:
var startDate = Xrm.Page.getAttribute('new_startdate').getValue();
var expiryDate = new Date();
expiryDate.setDate(startDate.getDate()+60); //Add 60 days
var expiryField = Xrm.Page.getAttribute('new_expirydate').setValue(expiryDate);
I can see here how to add 60 days, but I need to add exactly 2 months. Can someone help me about this?
Try to do something like following:
var startDate = Xrm.Page.getAttribute('new_startdate').getValue();
startDate.setMonth(startDate.getMonth() + 2);
Xrm.Page.getAttribute('new_expirydate').setValue(startDate);

Categories