How to get current day count of the quarter [duplicate] - javascript

I have two input dates taking from Date Picker control. I have selected start date 2/2/2012 and end date 2/7/2012. I have written following code for that.
I should get result as 6 but I am getting 5.
function SetDays(invoker) {
var start = $find('<%=StartWebDatePicker.ClientID%>').get_value();
var end = $find('<%=EndWebDatePicker.ClientID%>').get_value();
var oneDay=1000 * 60 * 60 * 24;
var difference_ms = Math.abs(end.getTime() - start.getTime())
var diffValue = Math.round(difference_ms / oneDay);
}
Can anyone tell me how I can get exact difference?

http://momentjs.com/ or https://date-fns.org/
From Moment docs:
var a = moment([2007, 0, 29]);
var b = moment([2007, 0, 28]);
a.diff(b, 'days') // =1
or to include the start:
a.diff(b, 'days')+1 // =2
Beats messing with timestamps and time zones manually.
Depending on your specific use case, you can either
Use a/b.startOf('day') and/or a/b.endOf('day') to force the diff to be inclusive or exclusive at the "ends" (as suggested by #kotpal in the comments).
Set third argument true to get a floating point diff which you can then Math.floor, Math.ceil or Math.round as needed.
Option 2 can also be accomplished by getting 'seconds' instead of 'days' and then dividing by 24*60*60.

If you are using moment.js you can do it easily.
var start = moment("2018-03-10", "YYYY-MM-DD");
var end = moment("2018-03-15", "YYYY-MM-DD");
//Difference in number of days
moment.duration(start.diff(end)).asDays();
//Difference in number of weeks
moment.duration(start.diff(end)).asWeeks();
If you want to find difference between a given date and current date in number of days (ignoring time), make sure to remove time from moment object of current date as below
moment().startOf('day')
To find difference between a given date and current date in number of days
var given = moment("2018-03-10", "YYYY-MM-DD");
var current = moment().startOf('day');
//Difference in number of days
moment.duration(given.diff(current)).asDays();

Try this Using moment.js (Its quite easy to compute date operations in javascript)
firstDate.diff(secondDate, 'days', false);// true|false for fraction value
Result will give you number of days in integer.

Try:
//Difference in days
var diff = Math.floor(( start - end ) / 86400000);
alert(diff);

This works for me:
const from = '2019-01-01';
const to = '2019-01-08';
Math.abs(
moment(from, 'YYYY-MM-DD')
.startOf('day')
.diff(moment(to, 'YYYY-MM-DD').startOf('day'), 'days')
) + 1
);

I made a quick re-usable function in ES6 using Moment.js.
const getDaysDiff = (start_date, end_date, date_format = 'YYYY-MM-DD') => {
const getDateAsArray = (date) => {
return moment(date.split(/\D+/), date_format);
}
return getDateAsArray(end_date).diff(getDateAsArray(start_date), 'days') + 1;
}
console.log(getDaysDiff('2019-10-01', '2019-10-30'));
console.log(getDaysDiff('2019/10/01', '2019/10/30'));
console.log(getDaysDiff('2019.10-01', '2019.10 30'));
console.log(getDaysDiff('2019 10 01', '2019 10 30'));
console.log(getDaysDiff('+++++2019!!/###10/$$01', '2019-10-30'));
console.log(getDaysDiff('2019-10-01-2019', '2019-10-30'));
console.log(getDaysDiff('10-01-2019', '10-30-2019', 'MM-DD-YYYY'));
console.log(getDaysDiff('10-01-2019', '10-30-2019'));
console.log(getDaysDiff('10-01-2019', '2019-10-30', 'MM-DD-YYYY'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.js"></script>

Also you can use this code: moment("yourDateHere", "YYYY-MM-DD").fromNow(). This will calculate the difference between today and your provided date.

// today
const date = new Date();
// tomorrow
const nextDay = new Date(new Date().getTime() + 24 * 60 * 60 * 1000);
// Difference in time
const Difference_In_Time = nextDay.getTime() - date.getTime();
// Difference in Days
const Difference_In_Days = Difference_In_Time / (1000 * 3600 * 24);

Related

Calculate the day difference between two time

I have two date format and I need to calculate the hour difference between both.
First date is current date.
Second Date is in below format :
var depDate = 25092018 //ddmmyyyy
var depTime = 08:35 //hh:mm
new Date function doesn't take date in format ddmmyyyy. How can input depDate in new Date function
I want to check the difference between current date and depDate.
Can anybody help ?
Your date in variable depDate hasn't valid format. You need to validate format of it using regex in .replace(). Then use Date.prototype.getTime() getting numeric value of date.
var depDate = "25092018";
var depTime = "08:35";
var dateStr = depDate.replace(/(\d{2})(\d{2})(\d{4})/, "$3-$2-$1")+"T"+depTime;
// dateStr => 2018-09-25T08:35
var timeDiff = Math.abs(new Date(dateStr).getTime() - new Date().getTime());
var diffDays = Math.ceil(timeDiff / (1000 * 3600 * 24));
// 1000 => to converting millisecond to second
// 3600 => to converting second to hour
// 24 => to converting hour to day
console.log(diffDays);
If you are using moment module, it would be much easy. Code a below:
let moment = require('moment');
let depDate = "27092018" //ddmmyyyy
let depTime = "08:35" //hh:mm
let date = moment(depDate, "DDMMYYYY").add(moment(depTime,"HH:mm"))
let difference = moment.duration(moment().diff(date)).asHours();
console.log(difference); // This would be the difference in hours.

JavaScript, how to create difference of date with moment.js

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

Javascript - Find out if date is between two dates, ignoring year

I need to find out if my date is between two dates (for checking birthday whether its between +/- 10 days of current date) without taking care of year (because for birthday we don't need year).
I have tried the following but its typical match and will not ignore year. If i ll compare only date and month then overlap on month end makes problems.
(moment(new Date()).isBetween(moment(date).add(10, 'days'), moment(date).subtract(10, 'days')));
Here is the solution that i was end up with.
const birthDate= new Date(birthDate);
birthDate.setFullYear(new Date().getFullYear());
const isBirthdayAround = Math.abs(birthday - new Date) < 10*24*60*60*1000;
And if you are using moment then:
const birthDate= new Date(birthDate);
birthDate.setFullYear(new Date().getFullYear());
const isBirthdayAround = moment(new Date()).isBetween(moment(birthDate).subtract(10, 'days'), moment(birthDate).add(10, 'days'));
if(Math.abs(birthday - new Date) < 10/*d*/ * 24/*h*/ * 60/*min*/ * 60/*secs*/ * 1000/*ms*/)
alert("somewhat in the range");
You can just work with dates as if they were milliseconds. Just get the difference by subtracting them, then check if its smaller than 10 days in milliseconds.
You can use momentjs with methods subtract and add to find any date you want.
Example:
moment().add(7, 'days'); // next 7 days
moment().subtract(7, 'days'); // 7 days ago
This may be help you.
var birthDate = new Date("05/16/1993");
var day = birthDate.getDate();
var month = birthDate.getMonth();
var currentDate = new Date();
var tempDate = new Date();
var oneDay = 1000 * 60 * 60 * 24
var dayDifference = 10 // you can set here difference
tempDate = new Date(tempDate.setMonth(month,day))
var timeDiff = tempDate.getTime() - currentDate.getTime();
timeDiff = Math.round(timeDiff / oneDay)
if(-dayDifference <= timeDiff && timeDiff <=dayDifference){
alert("matched")
}
else{
alert("not matched")
}

Javascript and mySQL dateTime stamp difference

I have a mySQL database in which I store the time in this format automatically:
2015-08-17 21:31:06
I am able to retrieve this time stamp from my database and bring it into javascript. I want to then get the current date time in javascript and determine how many days are between the current date time and the date time I pulled from the database.
I found this function when researching how to get the current date time in javascript:
Date();
But it seems to return the date in this format:
Tue Aug 18 2015 10:49:06 GMT-0700 (Pacific Daylight Time)
There has to be an easier way of doing this other than going character by character and picking it out from both?
You can build a new date in javascript by passing the data you receive from your backend as the first argument.
You have to make sure that the format is an accepted one. In your case we need to replace the space with a T. You may also be able to change the format from the back end.
Some good examples are available in the MDN docs.
var d = new Date("2015-08-17T21:31:06");
console.log(d.getMonth());
To calculate the difference in days you could do something like this:
var now = new Date();
var then = new Date("2015-08-15T21:31:06");
console.log((now - then)/1000/60/60/24);
You can select the difference directly in your query:
SELECT DATEDIFF(now(), myDateCol) FROM myTable;
the Date object has a function called getTime(), which will give you the current timestamp in milliseconds. You can then get the diff and convert to days by dividing by (1000 * 3600 * 24)
e.g.
var date1 = new Date()
var date2 = new Date()
var diffInMs = date2.getTime() - date1.getTime()
var diffInDays = diffInMs/(1000*3600*24)
Since none of the other answer got it quite right:
var pieces = "2015-08-17 21:31:06".split(' ');
var date = pieces[0].split('-');
var time = pieces[1].split(':');
var yr = date[0], mon = date[1], day = date[2];
var hour = time[0], min = time[1], sec = time[2];
var dateObj = new Date(yr, mon, day, hr, min, sec);
//if you want the fractional part, omit the call to Math.floor()
var diff = Math.floor((Date.now() - dateObj.getTime()) / (1000 * 60 * 60 * 24));
Note that none of this deals with the timezone difference between the browser and whatever you have stored in the DB. Here's an offset example:
var tzOff = new Date().getTimezoneOffset() * 60 * 1000; //in ms

how to find difference in days between day and month irrespective of years

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>

Categories

Resources