Need to calculate months between two dates in JQuery - javascript

I need to count total no of months between the two dates in months and years if not just months either any php snippet or ether js or jquery.
I display the data from backend using php tags {{ $job->job_start_date }} job_start_date is for start date and {{ $job->job_expiry_date }}) job_expiry_date is for end date.
I get my output as in this format 13-Oct-2016.
I tried this thing putting the values as hidden but couldn't get it work with parsing properly while adding new Date() to them
$(document).ready(function(){
var sDate = $("#monthStart").val();
var nDate = $("#monthEnd").val();
var sd = new Date(sDate );
var ed = new Date(nDate );
ed.setDate(ed.getDate() - sd.getDate());
alert(monthDiff(sd,ed));
});
function monthDiff(d1, d2) {
var months;
months = (d2.getFullYear() - d1.getFullYear()) * 12;
months -= d1.getMonth() + 1;
months += d2.getMonth();
return months <= 0 ? 0 : months;
}
need a easy solution in js jquery or php.

function MonthDiff(date1, date2) {
var Nomonths;
Nomonths= (date2.getFullYear() - date1.getFullYear()) * 12;
Nomonths-= date1.getMonth() + 1;
Nomonths+= date2.getMonth() +1; // we should add + 1 to get correct month number
return Nomonths <= 0 ? 0 : Nomonths;
}

function differenceInMonths($startDate, $endDate)
{
$date1 = new DateTime($startDate);
$date2 = new DateTime($endDate);
$interval = date_diff($date1, $date2);
return $interval->m + ($interval->y * 12) . ' months';
}
This way you get no. of months. Now you can calculate years if months >= 11.

Well in this case you can take advantage of moment.js library.
Assuming you have Date String in format like "1-Sept-2016" then we need to convert it to date and then apply moment. If you already have Date then you can directly apply the moment.
Demo :
var startDate = new Date('01-Sept-2016' );
var endDate = new Date('30-Oct-2016' );
var endMoment = moment(endDate);
var startMoment = moment(startDate);
//[days, years, months, seconds, ...]
console.log(endMoment.diff(startMoment, 'months'));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.15.1/moment.js"></script>
You can even specify the difference you want like days, months,years, seconds as specified above.
Reference : http://momentjs.com/

Here is a php solution:
$noMonth = 1 + (date('Y',strtotime($job->job_expiry_date)) - date('Y',strtotime($job->job_start_date))) * 12 + (date('m',strtotime($job->job_expiry_date)) - date('m',strtotime($job->job_start_date)))
The first part calculates the difference in years, multiplied by 12 results the number of month:
1 + (date('Y',strtotime($job->job_expiry_date)) -
date('Y',strtotime($job->job_start_date))) * 12
The second part calculates the number of months to be added or subtracted, as if the dates were in the same year:
(date('m',strtotime($job->job_expiry_date)) -
date('m',strtotime($job->job_start_date)))

Related

Javascript to count the number of days for a specific month between two dates [duplicate]

This question already has answers here:
How to calculate number of days between two dates?
(42 answers)
Closed last month.
I am new to javascript.
I have specific month columns (9/30/2022, 10/31/2022,11/30/2022). I have a contract with a start date and end date (spanning multiple months).
I need to determine the number of days the contract was active for a specific month column.
Example:
Contact Start Date: 09/15/2022
Contract End Date: 10/24/2022
Number of days the contract was active in Sept 2022 is 16.
I found the code below that gives me the contract period broken down for each month (i.e.) **9 - 17; 10 - 23; **
Thank you in advance for any assistance.
I found this code
function getDays() {
var dropdt = new Date(document.getElementById("arr").value);
var pickdt = new Date(document.getElementById("dep").value);
var result = "";
for (var year = dropdt.getFullYear(); year <= pickdt.getFullYear(); year++) {
var firstMonth = (year == dropdt.getFullYear()) ? dropdt.getMonth() : 0;
var lastMonth = (year == pickdt.getFullYear()) ? pickdt.getMonth() : 11;
for (var month = firstMonth; month <= lastMonth; month++) {
var firstDay = (year === dropdt.getFullYear() && month === firstMonth) ? dropdt.getDate() : 1;
var lastDay = (year === pickdt.getFullYear() && month === lastMonth) ? pickdt.getDate() : 0;
var lastDateMonth = (lastDay === 0) ? (month + 1) : month
var firstDate = new Date(year, month, firstDay);
var lastDate = new Date(year, lastDateMonth, lastDay);
result += (month + 1) + " - " + parseInt((lastDate - firstDate) / (24 * 3600 * 1000) + 1) + "; ";
}
}
return result;
}
function cal() {
if (document.getElementById("dep")) {
document.getElementById("number-of-dates").value = getDays();
}
Calculate
`
The following snippet will generate an object res with the keys being zero-based month-indexes ("8" is for September, "9" for October, etc.) and the values are the number of days for each of these months:
const start=new Date("2022-09-15");
const end=new Date("2022-11-24");
let nextFirst=new Date(start.getTime()), month, days={};
do {
month=nextFirst.getMonth();
nextFirst.setMonth(month+1);nextFirst.setDate(1);
days[month]=Math.round(((nextFirst<end?nextFirst:end)-start)/86400000);
start.setTime(nextFirst.getTime());
} while(nextFirst<end)
console.log(days);
This can be extended into a more reliable function returning a year-month combination:
function daysPerMonth(start,end){
let nextFirst=new Date(start.getTime()), year, month, days={};
do {
year=nextFirst.getFullYear();
month=nextFirst.getMonth();
nextFirst.setMonth(month+1);nextFirst.setDate(1);
days[`${year}-${String(1+month).padStart(2,"0")}`]=Math.round(((nextFirst<end?nextFirst:end)-start)/86400000);
start.setTime(nextFirst.getTime());
} while(nextFirst<end)
return days;
}
[["2022-09-15","2022-11-24"],["2022-11-29","2023-02-04"]].forEach(([a,b])=>
console.log(daysPerMonth(new Date(a),new Date(b))));
Managing and calculating dates, times, and date-times are notoriously finicky in javascript and across browsers. Rather than trying to define your own logic for this use the famous Moment.js library.
In particular to calculate the length between two dates you can utilize the diff function between two moments
var a = moment([2007, 0, 29]);
var b = moment([2007, 0, 25]);
var diff = a.diff(b, 'days') // 1
console.log(diff);
<script src="https://momentjs.com/downloads/moment.js"></script>
The supported measurements are years, months, weeks, days, hours, minutes, and seconds.

Javascript - comparing two dates ( minus X days) to see whether it's true or false

I am trying to execute a code if a date (from a cookie) is older than about 2 days. More or less, it doesnt have to be precise.
The cookie value is : 2022-06-27T23:28:02.816Z
function getCookie(name) {
var value = "; " + document.cookie;
var parts = value.split("; " + name + "=");
if (parts.length == 2) return parts.pop().split(";").shift();
}
Using :
getCookie(name) and : .slice(0, 10);
Returns : 2022-06-27
Therefore I now have a YYYY-MM-DD value
var stuff_cookiename = getCookie("cookiename").slice(0, 10);
Converting to a date format :
var t_date_refuscmp_todate = Date.parse(stuff_cookiename);
I now have something like this : 1656288000000
Now I want to compare it NOW's date - 2 days
So I do :
var t_date_verif = new Date();
var t_date_verif_format = tc_date_verif.setDate(tc_date_verif.getDate() - 2);
Which brings me something like : 1656199936800
=====================
But if i compare my cookiedate vs todaysdate -2 days, it doesnt always seem to be working correctly.
t_date_refuscmp_todate < t_date_verif_format !!!
Any idea of what I am not doing right?
Maybe there is something a lot easier to do :)
Thanks !
^ A more specific(to your question)and simpler answer in my opinion
var diff = Date.now() - new Date("2022-06-25T23:28:02.816Z");
if(diff <= 1000 * 60 * 60 * 24 * 2){
console.log("less than 2 days old");
}else{
console.log("more than 2 days old");
}
Idea
Parse the cookie and the current datetime, convert it into epoch ms, sompute the difference in days.
Code
let s_dtCookie = "2022-06-27T23:28:02.816Z"
, n_epochCookie = (new Date(s_dtCookie)).getTime()
, n_epochNow = (new Date()).getTime()
, n_deltaDays = (n_epochNow - n_epochCookie) / (24 * 3600 * 1000)
;
console.log(`Cookie time '${s_dtCookie}' is ${n_deltaDays} days in the past.`);
Reference
MDN JS docs, Date.getTime() section.

Convert number of days left into years, months, days [duplicate]

This question already has answers here:
Difference between two dates in years, months, days in JavaScript
(34 answers)
How to get difference between 2 Dates in Years, Months and days using moment.js
(3 answers)
How to get the difference of two dates in mm-dd-hh format in Javascript
(3 answers)
Closed 2 years ago.
I am trying to get the difference between two dates (my birthday and the current date to get the time left until my birthday), But I want the output format in ('Year/Months/Days); How can I do that? that's what I've tried so far :
const birthday = new Date ('11-20-2021').getTime();
const today = new Date ().getTime();
const dys = (1000*60*60*24);
const months = (dys*30);
let differance = birthday-today ;
const formatted = Math.round(differance/dys);
console.log(formatted);`
thank you in advance
How do you feel about the modulo operator? :)
This is a common math operation, like finding change or such. Think of it this way, if you have a large number of days, say 397, you can get number of years by doing integer division (1), then you can get the number of days left by doing modulo by a year to get the remainder (in days) 397%365 = 32. Then you can repeat the process to get number of months remaining (1...assuming 30 day month) in that and again, modulo to get the final number of days 2 ...
I'm no javascript pro, but I think you need to use Math.floor(quotient) to get the result of division in integer format.
this example compares between the current date and the date 2100/0/14 try the same concept in the example and i hope it helps:
var today, someday, text;
today = new Date();
someday = new Date();
someday.setFullYear(2100, 0, 14);
if (someday > today) {
text = "Today is before January 14, 2100.";
} else {
text = "Today is after January 14, 2100.";
}
document.getElementById("demo").innerHTML = text;
Working with dates and differences can be difficult because there are a lot of edge cases. which is why I prefer to let a dedicated library handle this, like https://momentjs.com/
moment has a plugin (https://www.npmjs.com/package/moment-precise-range-plugin) which does exactly what you are looking for:
import moment from 'moment';
import 'moment-precise-range-plugin';
var m1 = moment('2014-01-01 12:00:00','YYYY-MM-DD HH:mm:ss');
var m2 = moment('2014-02-03 15:04:05','YYYY-MM-DD HH:mm:ss');
var diff = moment.preciseDiff(m1, m2, true); // {years : 0, months : 1, days : 2, hours : 3, minutes : 4, seconds : 5}
var str = `Years: ${diff.years}, Months: ${diff.months}, Days: ${diff.days} `; // 'Years: 0, Months: 1, Days: 2'
If I got you right, I've done it this way.
Haven't touched your original code, but added a function that calculates the dateTime output of the total days of difference.
const birthday = new Date('11-20-2021').getTime();
const today = new Date().getTime();
const dys = (1000 * 60 * 60 * 24);
const months = (dys * 30);
let totalDayserance = birthday - today;
const formatted = daysToDateTime(totalDayserance / dys);
console.log(formatted);
function daysToDateTime(totalDays) {
var baseVal = '';
var formedValues = [
['Years', 365],
['Months', 30],
['Days', 1]
];
for (var i = 0; i < formedValues.length; i++) {
var valueByGroup = Math.floor(totalDays / formedValues[i][1]); //by months
if (valueByGroup >= 1) {
baseVal += (valueByGroup + formedValues[i][0]) + ', ';
totalDays -= valueByGroup * formedValues[i][1];
}
}
return baseVal;
}

How to cast a date column value in javascript, and how to increase this date variable?

I am using sharepoint 2013 online. I have created a custom list. On this list I have used JSLink to show an icon in a column. I would like to do some logic to show a red or a green icon. I have now in js 2 dates. The date from my column from the current item and the date of today. I would like to do the following check:
var contractEndDate = ctx.CurrentItem.Contract_x0020_einddatum;
var today = new Date();
if((contractEndDate + 10 days) > today)
{
return "<img src='https://myCompany.sharepoint.com/sites/teams/Sales/SiteAssets/green.png'/>";
}
else
{
return "<img src='https://myCompany.sharepoint.com/sites/teams/Sales/SiteAssets/red.png'/>";
}
How can I cast the var contractEndDate to a date? And how can I increase it with 10 days?
Add 10 and compare:
var endPlus10 = new Date(contractEndDate);
endPlus10.setDate(contractEndDate.getDate() + 10);
if (endPlus10 > today) ...
The value returned by the getTime method is the number of milliseconds since 1 January 1970 00:00:00 UTC. You can compute the number of milliseconds in a day (see one_day variable) and compare dates.
See my JS Fiddle, http://jsfiddle.net/cVm59/1/
var contractEndDate = new Date("2-18-2014"),
today = new Date(),
one_day = 1000 * 60 * 60 * 24;
if((contractEndDate.getTime() + (one_day*10)) > today.getTime())
{
console.log("Less than 10 days ago");
}
else
{
console.log("More than 10 days ago");
}
This should be what you are looking for:
var contractEndDate = ctx.CurrentItem.Contract_x0020_einddatum;
var today = new Date();
var CED = new Date(contractEndDate);
CED.setDate(CED.getDate() + 10);
if(CED > today)
{
Create CED as a new date and then using the setDate this just adds 10 days before you make your comparison. You could clean this up and just set your contractEndDate as a new Date, but up to you.

Javascript - Age Verification

Hey javascript masters,
Attempting to create an age verification page to a client's site. Code below is not functioning as it doesn't matter what year you select, it will still allow you to enter the site. Not sure what I should be looking at to correct.
Any help is appreciated.
<script type="text/javascript"><!--
function checkAge(f){
var dob=new Date();
var date=dob.getDate();
var month=dob.getMonth() + 1;
var year=dob.getFullYear();
var cmbmonth=parseInt(document.getElementById("cmbmonth").options[document.getElementById("cmbmonth").selectedIndex].value);
var cmbday=parseInt(document.getElementById("cmbday").options[document.getElementById("cmbday").selectedIndex].value);
var cmbyear=parseInt(document.getElementById("cmbyear").options[document.getElementById("cmbyear").selectedIndex].value);
age=year-cmbyear;
if(cmbmonth>month){age--;}
else{if(cmbmonth==month && cmbday>=date){age--;}}
if(cmbmonth==0){alert("You must enter the month you were born in.");return false;}
else if(cmbday==0){alert("You must enter the day you were born on.");return false;}
else if(cmbyear==2005){alert("You must enter the year you were born in.");return false;}
else if(age<13){alert("You are unable to view this site!");location.replace("http://www.dharmatalks.org");return false;}
else{return true;}
}
// --></script>
Calculating age in years, months and days is a bit trickier than it should be due to the differences in month and year lengths. Here's a function that will return the difference between two dates in years, months, days, hours, minutes and seconds.
function dateDifference(start, end) {
// Copy date objects so don't modify originals
var s = new Date(+start);
var e = new Date(+end);
var timeDiff, years, months, days, hours, minutes, seconds;
// Get estimate of year difference
years = e.getFullYear() - s.getFullYear();
// Add difference to start, if greater than end, remove one year
// Note start from restored start date as adding and subtracting years
// may not be symetric
s.setFullYear(s.getFullYear() + years);
if (s > e) {
--years;
s = new Date(+start);
s.setFullYear(s.getFullYear() + years);
}
// Get estimate of months
months = e.getMonth() - s.getMonth();
months += months < 0? 12 : 0;
// Add difference to start, adjust if greater
s.setMonth(s.getMonth() + months);
if (s > e) {
--months;
s = new Date(+start);
s.setFullYear(s.getFullYear() + years);
s.setMonth(s.getMonth() + months);
}
// Get remaining time difference, round to next full second
timeDiff = (e - s + 999) / 1e3 | 0;
days = timeDiff / 8.64e4 | 0;
hours = (timeDiff % 8.64e4) / 3.6e3 | 0;
minutes = (timeDiff % 3.6e3) / 6e1 | 0;
seconds = timeDiff % 6e1;
return [years, months, days, hours, minutes, seconds];
}
You can abbreviate the above just after the year part and return just that if you want.
Note that in your code:
var cmbmonth=parseInt(document.getElementById("cmbmonth").options[document.getElementById("cmbmonth").selectedIndex].value);
can be:
var cmbmonth = document.getElementById("cmbmonth").value;
There is no need for parseInt, the Date constructor will happily work with string values. If you have used calendar month numbers for the values (i.e. Jan = 1) then subtract 1 before giving it to the Date constructor, but simpler to use javascript month indexes for the values (i.e. Jan = 0).
You can then do:
var diff = dateDifference(new Date(cmbyear, cmbmonth, cmbdate), new Date());
if (diff[0] < 18) {
// sorry, under 18
}

Categories