I am working on requirement and need to check about my logic that I have implemented. Please help.
I want to get the 1 month,3 month and 6 month return % of stock price from current date.
I have a table which have date and price array field as shown.
{
"_id" : ObjectId("5a65d0e7bfd103df081a75a8"),
"aId" : 93,
"values" : [
{
"date" : "2018-02-06",
"Price" : 27.9057
},
{
"date" : "2018-02-05",
"Price" : 28.0406
}
]
}
My logic
Iterate through the date,price array and pass the date to a function which will calculate days difference.
function differenceFromTodayInDays(FromDate) {
var currentDate = new Date();
var previousDate = new Date(FromDate);
var difference = Math.floor(currentDate.getTime() - previousDate.getTime());
var secs = Math.floor(difference / 1000);
var mins = Math.floor(secs / 60);
var hours = Math.floor(mins / 60);
var days = Math.floor(hours / 24);
return days;
}
Push the days into different arrays if days = 30,31 or 60,61 or 91,90,92,93
if (differenceInDays == 30 || differenceInDays == 31) {
$scope.days30.push(index);
so overall till now
$scope.timeDiffInDays = function(index, otherDate) {
$scope.days30 = [];
var differenceInDays = differenceFromTodayInDays(otherDate);
if (differenceInDays == 30 || differenceInDays == 31) {
$scope.days30.push(index);
}
}
Here I have index and can take the price value of that index and calculate return % from current value.
My Concerns are
Values in array are increasing daily and it will slow down process.
Date Difference of 30/31/60/61/90/91 is not available sometimes as some days are holidays and those values are not there in array.so it is hard to get return %.
I am looking for some efficient logic for this.
Thanks,
J
If I understand correctly why you are including date part in your code? Get month and year only and write a code like (endyear-startyear)*12+(endmonth-startmonth)- (enddate>=startdate?0:1).
I don't have laptop support now(writing from phone). I think getMonth() and getFullYear() will help you to do this
Related
I modified the code below to create a time string which looks exactly the way I want it. It is how my Timex watch displays time.
Is there a native way to do this? I feel like I must have re-invented the wheel as surely many have needed this method before me.
const api = {};
// gets a time string which is human readable using the Date object
api.getTime = function() {
const date = new Date();
// get minutes and add a 0 if needed
let min = date.getMinutes();
min = (parseInt(min, 10) < 10 ? '0' : '') + min;
// get hours, determine AM or PM and change to 12 hours
// not preceding 0 is needed
let hour = date.getHours();
const amPm = hour >= 12 ? 'PM' : 'AM';
hour = ( hour % 12 ) || 12;
// get seconds and add a 0 if needed
let sec = date.getSeconds();
sec = (parseInt(sec, 10) < 10 ? '0' : '') + sec;
return `${hour}:${min}:${sec} ${amPm}`;
}
module.exports = api;
I think it is definitely helping if you take a look at toLocaleTimeString(), from the documentation:
Return the time portion of a Date object as a string, using locale conventions.
You can test out this function as the following:
const date = new Date().toLocaleTimeString();
console.log(date);
I hope that helps!
What I am trying to accomplish is multiple countdowns with different expiration dates. I have a code snippet from Codepen, I used as a starting point that works for just one countdown. I am also hoping that no matter whether the viewer is in California, or Georgia the expiration will know what the time zone is. I added the suggested getTimezoneOffset() to deal with different time zones. Which causes the countdown to multiply the days remaining to an absurd number that is 50 years in the future. When I remove that, it is fine. So I have not figured out how to implement that suggestion correctly. Through much trial and error I did successfully create a duplicate countdown with a different expiration date. The only thing I don't understand still is how to implement getTimezoneOffset() so that it does not display 17,893 and 17,883 days (50 years worth of days). I am a trial and error javascript modifier. I try stuff until something is no longer broken.
var countDownDate = new Date("DEC 27, 2018").getTime();
var countDownDate2 = new Date("DEC 17, 2018").getTime();
// COPY FEED
var data = {
// OFFER 1
one: "Offer One",
two: "Free Product",
three: "Today Only",
// OFFER 2
four: "Offer Two",
five: "Free Pickup",
six: "<span id='daysLeft'></span> <span id='plural'></span>",
seven: "Expires: Dec. 27, 2018",
// OFFER 3
eight: "Offer Three",
nine: "<span id='daysLeft2'></span> <span id='plural2'></span>",
ten: "Expires: Dec. 17, 2018",
};
// LOOP THROUGH KEYS TO GET ALL ELEMENT IDs & CREATE VARIABLES
function bannerFunc() {
for (key in data) {
if (data.hasOwnProperty(key)) {
var value = data[key];
var key = document.getElementById('" + key + "');
}
}
// ASSIGN OBJECT VALUES TO VARIABLES
one.innerHTML = data.one;
two.innerHTML = data.two;
three.innerHTML = data.three;
four.innerHTML = data.four;
five.innerHTML = data.five;
six.innerHTML = data.six;
seven.innerHTML = data.seven;
eight.innerHTML = data.eight;
nine.innerHTML = data.nine;
ten.innerHTML = data.ten;
// DATE CODE
var x = setInterval(function() {
var now = new Date().getTimezoneOffset(),
amountLeft = countDownDate - now,
days = Math.floor(amountLeft / (1000 * 60 * 60 * 24) + 1),
plural = document.getElementById('plural');
plural.innerHTML = days + ' Days Left';
if( days < 2 && days > 0 ){
plural.innerHTML = days + ' Day Left';
}
if( days <= 0 ){
plural.innerHTML = 'Expired';
}
var now = new Date().getTimezoneOffset(),
amountLeft = countDownDate2 - now,
days = Math.floor(amountLeft / (1000 * 60 * 60 * 24) + 1),
plural = document.getElementById('plural2');
plural2.innerHTML = days + ' Days Left';
if( days < 2 && days > 0 ){
plural2.innerHTML = days + ' Day Left';
}
if( days <= 0 ){
plural2.innerHTML = 'Expired';
}
}, 1000);
}
bannerFunc();
Use the getTimeZoneOffset for your date calculations. Then define all your dates as UTC dates. (https://www.w3schools.com/jsref/jsref_gettimezoneoffset.asp).
More about JS Dates
I am having a problem with creating an error message on a page where there is a "from date:", and a "to date:". If the difference between the two dates is greater than or equal to 60 days, I have to put up an error message.
I am trying to use moment.js and this is what my code is looking like now. It was recommended that I use it in knockout validation code. this is what it looks like right now:
var greaterThan60 = (moment().subtract('days', 60) === true) ? "The max range for from/to date is 60 days." : null;
I am still not sure how to make it greater than 60 days, not just equal to 60 days. This is what my boss gave me to help.
Reference site for moment().subtract
moment.js provides a diff() method to find difference between dates. please check below example.
var fromDate = 20180606;
var toDate = 20180406;
var dif = moment(fromDate, 'YYYYMMDD').diff(moment(toDate, 'YYYYMMDD'),'days')
console.log(dif) // 61
subtract returns a new moment object. So checking for true always returns false. You can use range and diff to calculate a diff in days and check that:
let start = moment('2016-02-27');
let end = moment('2016-03-02');
let range = moment.range(start, end);
let days = range.diff('days');
let error = null;
if (days > 60) {
error = "The max range for from/to date is 60 days.";
}
You Can try this.
var date = Date.parse("2018-04-04 00:00:00");
var selectedFromDate = new Date(date);
var todayDate = new Date();
var timedifference = Math.abs(todayDate.getTime() - selectedFromDate.getTime());
var daysDifference = Math.ceil(timedifference/(1000 * 3600 * 24));
just use if else loop for greater than 60 days validation.
if(daysDifference > 60)
{
alert("From Date should be less than 2 months");
}
Use the .isSameOrAfter function to compare if the end value is greater than or equal to the start value plus sixty days. Example:
var greaterThan60 = toDate.isSameOrAfter(startDate.add(60, 'days'));
where toDate is your end time as a moment object and startDate is the start time as a moment object. If the end date is greater than or equal to 60 days after the start date, greaterThan60 will be true.
References:
isSameOrAfter
add
My scheduled script sets a field to store an accrued late fee charge for each day an invoice is overdue. I am comparing the current system time against due date to work out the number of days overdue. However, I didn't take into consideration to exclude the weekend. How can I use my existing code to do this?
var current_date = nlapiStringToDate(nlapiDateToString(new Date()));
var dd = invoice.getFieldValue('duedate');
var due_date = nlapiStringToDate(dd);
if (due_date < current_date) {
//Other Calculations
var days_overdue = DateOverdue(current_date, due_date);
}
function DateOverdue(current_date, due_date) {
var time_difference = Math.abs(due_date.getTime() - current_date.getTime());
var no_days_overdue_by = Math.ceil(time_difference / (1000 * 3600 * 24));
return no_days_overdue_by;
}
The following works. Note the extra dates are to clear issues from comparing time stamps without hours, minutes and seconds. Not strictly needed for the current_date given how you are generating it but it makes a more general function.
NOTE: I don't believe you should be able to compare dates with d1 < d2.
function daysOverdue(currentDate, dueDate){
var days = 0;
var due = new Date(dueDate.getFullYear(), dueDate.getMonth(), dueDate.getDate(), 0, 0, 0);
var fromTS = new Date(currentDate.getFullYear(), currentDate.getMonth(), currentDate.getDate(), 0, 0, 0).getTime();
if(due.getTime() >= fromTS) return 0; // not overdue
while(due.getTime() < fromTS){
if(due.getDay() !== 0 && due.getDay() != 6) days++;
due.setDate(due.getDate() + 1);
}
return days;
}
I want to know the difference between to two dates irrespective of year..
For Example : format date/month/year
For example difference of today date to some date lets take 01/06
The expected answer for this will be around 185 days..
I tried below example..Let me know whats wrong with this
var a = moment('06/01','M/D');
console.log(a);
var b = moment();
console.log(b);
var diffDays = b.diff(a, 'days');
alert(diffDays);
I dont want to use momet.js atmost. If it can be done with javascript its so good for me.
A nice trick could be to set the year to always the same.
var a = moment('2015/06/01','Y/M/D');
console.log(a);
var b = moment().set('year', 2015);
console.log(b);
var diffDays = b.diff(a, 'days');
alert(diffDays);
The problem about your question in general is how to deal with leap years; how the script should know the difference between 2/20 and 3/1 ? You have to consider how to solve this.
Barth Zaleweski is 100% on track with that. If you want to use straight javascript:
var today = new Date();
var otherDate = new Date(today);
otherDate.setMonth(5); // Set the month (on scale from 0 to 11)
otherDate.setDate(1); // set day
var seconds = (otherDate.getTime() - today.getTime()) / 1000;
var minutes = seconds / 60;
var hours = minutes / 60;
var days = hours / 24;
console.log(days);
There are methods for setting hour/minute/second as well, but if you don't do anything they'll be the same as the start, and you can obviously call those same methods on your start time if you don't want to use today.
Can try using this:
var str1 = '06/01', str2 = '02/28', d1, d2, diff;
function setDate(str, date) {
var date = new Date(),
dateParts = str.split('/'),
monthIndex = parseInt(dateParts[0], 10) - 1,
day = parseInt(dateParts[1], 10);
date.setMonth(monthIndex);
date.setDate(day);
return date
}
d1 = setDate(str1);
d2 = setDate(str2);
diff = Math.round(Math.abs((d1 - d2) / (24 * 60 * 60 * 1000)))
console.log(diff) // returns 93
The rounding is due to differences in daylight savings (or other locale time shifts within the year) that can cause decimal values returned.
It is probably better to use UTC for this
If current year is leap year and dates span end of February then Feb 29 would also be counted
DEMO
If it is this year then I am getting a difference of 147 using a library that I have been working on (AstroDate) which doesn't rely on javascript's Date object, it's all done with pure math.
require.config({
paths: {
'astrodate': '//rawgit.com/Xotic750/astrodate/master/lib/astrodate'
}
});
require(['astrodate'], function (AstroDate) {
"use strict";
var diff = new AstroDate("2015","6","1").jd() - new AstroDate("2015","1","5").jd();
document.body.appendChild(document.createTextNode(diff));
});
<script src="http://requirejs.org/docs/release/2.1.8/minified/require.js"></script>
If it was next year, which is a leap year then I am getting 148
require.config({
paths: {
'astrodate': '//rawgit.com/Xotic750/astrodate/master/lib/astrodate'
}
});
require(['astrodate'], function (AstroDate) {
"use strict";
var diff = new AstroDate("2016", "6", "1").jd() - new AstroDate("2016", "1", "5").jd();
document.body.appendChild(document.createTextNode(diff));
});
<script src="http://requirejs.org/docs/release/2.1.8/minified/require.js"></script>