var frommonth="201912";
var tomonth="201810";
From Above Two Month how i will get difference between two Month in JavaScript?
var date1 = new Date(fromdate);
var date2 = new Date(todate);
var timeDiff = Math.abs(date2.getTime() - date1.getTime());
var diffDays = Math.ceil(timeDiff / (1000 * 3600 * 24));
var fromYear=date1.getFullYear();
var toYear=date2.getFullYear();
var diffyear =toYear-fromYear;
new Date() dont parse YYYYMM. It consider 201912 as year
So Use match() to parse YYYYMM
var from = "201912";
var to = "201810";
function parseMonth(str) {
return str.match(/(\d{4})(\d{2})/).splice(1).map(Number)
}
var [fromY, fromM] = parseMonth(from)
var [toY, toM] = parseMonth(to)
var result = (fromY - toY) * 12 + (fromM - toM)
console.log(result, 'months')
You can pass the frommonth and tomonth to the function as parameters and can perform calculation of difference..
Here new Date(frommonth.substring(0,4), frommonth.substring(4), 0) denotes,
-> frommonth.substring(0,4) => Getting the year from the string
-> frommonth.substring(4) => Getting the month from the string
-> 0 => Setting up date as 0.
And the same has been considered for tomonth as well..
Also Math.round(timeDiff / (2e3 * 3600 * 365.25)); is made to consider the leap year as well..
const frommonth = "201912";
const tomonth = "201810";
const diffInMonths = (end, start) => {
var timeDiff = Math.abs(end.getTime() - start.getTime());
return Math.round(timeDiff / (2e3 * 3600 * 365.25));
}
const result = diffInMonths(new Date(frommonth.substring(0,4), frommonth.substring(4), 0), new Date(tomonth.substring(0,4), tomonth.substring(4), 0));
//Diff in months
console.log(result);
I want correct results even if month has 31 days or 30 days.
var startDt = $("input[id=StartDate_" + i + "]").val();
var endDt = $("input[id=EndDate_" + i + "]").val();
var diff = new Date(Date.parse(endDt) - Date.parse(startDt));
var days = ((diff / 1000 / 60 / 60 / 24) + 1);
if (SelVal == "Monthly") {
$("#div" + i).html(Math.ceil(days / 30));
}
if (SelVal == "Semi-monthly") {
$("#div" + i).html(Math.ceil(days / 15));
}
I want to calculate difference where is Start Date is 10 April 2019 and End Date is 14 May 2019. I want monthly and semi-monthly. For this example:
Number of months difference would be 1
Semi-monthly difference would be 3 as mid of the month is
counted by date 15 of every month.
For example the billing of any center takes place every 1st and 15th date of the month and I need number of billings between two dates.
Okay try this:
var date1 = new Date("10/31/2019");
var date2 = new Date("12/1/2019");
var timeDiff = Math.abs(date2.getTime() - date1.getTime());
var diffDays = Math.ceil(timeDiff / (1000 * 3600 * 24));
console.log(diffDays)
console.log("months: "+ (Math.floor(diffDays/30)));
console.log("days: "+ (diffDays%30));
have a look to the code snippet
var date1 = new Date("10/31/2019");
var date2 = new Date("12/1/2019");
var timeDiff = Math.abs(date2.getTime() - date1.getTime());
var diffDays = Math.ceil(timeDiff / (1000 * 3600 * 24));
console.log(diffDays)
console.log("months: "+ (Math.floor(diffDays/30)));
console.log("days: "+ (diffDays%30));
I have a countdown timer timer constructed but it's just using getTime(), i'm unsure how to adjust this so it is the correct timezone i want (PDT/PT)
var countdownTimer = setInterval(countdownTick, 1000);
function countdownTick() {
jQuery('ul.countdown').each(function() {
var date = jQuery(this).attr('data-date').split('-'); // Create date array from attribute
var time = jQuery(this).attr('data-time').split('-'); // Create time array from attribute
for (var i = 0; i < date.length; i++) {
date[i] = parseInt(date[i]);
}
for (var i = 0; i < time.length; i++) {
time[i] = parseInt(time[i]);
}
var today = new Date();
var theDate = new Date(date[0], (date[1] - 1), date[2], time[0], time[1]);
if (theDate.getTime() > today.getTime()) { // If the target date is in the future
countdownCalc(this, theDate, today); // Calculate how much time there is until the target date
}
});
}
function countdownCalc(obj, targetDate, currentDate) {
var oneDay = 1000 * 60 * 60 * 24;
var oneSecond = 1000;
var output = (targetDate.getTime() - currentDate.getTime());
var day = Math.floor(output / oneDay);
var hour = Math.floor((output - (day * oneDay)) / (1000 * 60 * 60));
var minute = Math.floor((output - (hour * (1000 * 60 * 60) + (day * oneDay))) / (1000 * 60));
var second = Math.floor((output - ((minute * 60000) + (hour * 1000 * 60 * 60) + (day * oneDay))) / 1000);
jQuery(obj).html('<li><span class="countdown-label">DAYS</span><span class="countdown-number">' + day + '</span></li><li><span class="countdown-label">HOURS</span><span class="countdown-number">' + hour + '</span></li><li><span class="countdown-label">MINUTES</span><span class="countdown-number">' + minute + '</span></li><li><span class="countdown-label">SECONDS</span><span class="countdown-number">' + second + '</span></li>');
}
https://jsfiddle.net/4nag4h5v/
Here is where plugins become useful, using moment-timezone.js
We are able to do something is simple as:
let time = Date.now();
moment(time).tz("YOURTIMEZONE").format('x') // get timestamp (in milliseconds
Without using an external library, the simplest way to do it is by using an offset between your local and target timezones:
let today = new Date(),
localOffset = -(today.getTimezoneOffset()/60),
targetOffset = -8,
netOffset = targetOffset - targetOffset;
const d = new Date(new Date().getTime() + netOffset * 3600 * 1000);
I have a JavaScript Date() object and I only need the milliseconds of the current time; I don't want any dates.
var myDate = new Date();
// get millis only for time and not for date
Is there a possibility to do this?
All you need to do is:
var millis = myDate.getMilliseconds();
You could use the remainder of a day length of the epoc.
var d = +(new Date());
console.log(d);
d = d % (1000 * 60 * 60 * 24);
console.log(d);
console.log('h', d / (1000 * 60 * 60) | 0);
console.log('m', (d % (1000 * 60 * 60)) / (1000 * 60) | 0);
console.log('s', (d % (1000 * 60)) / 1000 | 0);
If I understand correctly you want the ms that have elapsed in the day current day?
You could try something like
var now = new Date().getTime();
var startOfDay = new Date().setHours(0,0,0,0);
var ms = now - startOfDay;
console.log(now);
console.log(startOfDay);
console.log(ms);
Sure is.
Step 1: Declare a variable as a date.
var today = new Date();
Step 2: Redefine variable with .getHours() method.
today = today.getHours();
Step 3: Divider by milliseconds in a day.
today = today / 86400000;
function getMs() {
var d = new Date();
var n = d.getMilliseconds();
document.getElementById("setMs").innerHTML = n;
}
<button onclick="getMs()">Click me</button>
<p id="setMs"></p>
Hope it helps.
var date1 = new Date("04.11.2016");
var date2 = new Date("19.11.2016");
var timeDiff = Math.abs(date2.getTime() - date1.getTime());
var diffDays = Math.ceil(timeDiff / (1000 * 3600 * 24));
alert(diffDays);
Trying get different between those Dates, but my date format is that "04.11.2016", Result show NaN
var date1 = new Date("11/04/2016");
var date2 = new Date("11/19/2016");
var timeDiff = Math.abs(date2.getTime() - date1.getTime());
var diffDays = Math.ceil(timeDiff / (1000 * 3600 * 24));
alert(diffDays);
change the format of date.
it should be MM/DD/YYYY
Hope this helps.
The easiest way is to use moment.js library:
var date1 = moment('04.11.2016', 'MM.DD.YYYY'),
date2 = moment('19.11.2016', 'MM.DD.YYYY'),
diffDays = date2.diff(date1, 'days'); // you can wrap it in Math.abs()
The ugly js way:
var input1 = '04.11.2016',
parts1 = input1.split('.'),
date1 = new Date(parts1[2], parts1[1], parts1[0]),
input2 = '19.11.2016',
parts2 = input2.split('.'),
date2 = new Date(parts2[2], parts2[1], parts2[0]),
timeDiff = Math.abs(date2.getTime() - date1.getTime()),
diffDays = Math.ceil(timeDiff / (1000 * 3600 * 24));
Change the Month and Date order First should be month then date... MM/DD/YYYY
var date1 = new Date("11.04.2016");
var date2 = new Date("11.19.2016");
var timeDiff = Math.abs(date2.getTime() - date1.getTime());
var diffDays = Math.ceil(timeDiff / (1000 * 3600 * 24));
alert(diffDays);
Your second date is incorrect. Parser is considering this format MM.DD.YYY and you have supplied out of range month.
var date1 = new Date("04.11.2016");
var date2 = new Date("09.11.2016");
var timeDiff = Math.abs(date2.getTime() - date1.getTime());
var diffDays = Math.ceil(timeDiff / (1000 * 3600 * 24));
alert(diffDays);
A date consists of a year, a month, a day, an hour, a minute, a second, and milliseconds.
Date objects are created with the new Date() constructor.
There are 4 ways of initiating a date:
new Date()
new Date(milliseconds)
new Date(dateString)
new Date(year, month, day, hours, minutes, seconds, milliseconds)
so you can split them and then use it
Just change the first two lines as below
var date1 = new Date(2016,11,4);
var date2 = new Date(2016,11,19);
new date("mm dd yyyy") format was wrong
(function () {
var date1 = new Date("11 04 2016");
var date2 = new Date("11 19 2016");
var timeDiff = Math.abs(date2.getTime() - date1.getTime());
var diffDays = Math.ceil(timeDiff / (1000 * 3600 * 24));
console.log(diffDays);
})()
JS expects date to in MM-DD-YYYY and not DD-MM-YYYY. Ideal way would be to use moment.js, but you can use something like this:
function createCustomDate(dateString){
var dateArr = dateString.split(/[^0-9]/).reverse().join("-")
return new Date(dateArr);
}
var dateStr1 = "04.11.2016";
var dateStr2 = "19.11.2016";
var date1 = createCustomDate(dateStr1);
var date2 = createCustomDate(dateStr2);
var timeDiff = Math.abs(date2.getTime() - date1.getTime());
var diffDays = Math.ceil(timeDiff / (1000 * 3600 * 24));
console.log(diffDays);
new Date("19.11.2016");
this is Invalid Date. So, difference is be NaN .
change the format to mm/dd/yyyy and it will work.
You can use moment.js,
d = moment('11.16.2016') // here date format was in "MM.DD.YYYY"
e = moment('11.04.2016') // here date format was in "MM.DD.YYYY"
getDiffbydays = e.diff(d,'days') // get diff by days you can use day
getDiffbyyears = e.diff(d,'year') // get diff by years you can use year
getDiffbymonth = e.diff(d,'month') // get diff by months you can use month
Check this solution which uses a function called getDate to convert the date string of the format "04.11.2016" to a JavaScript Date object.
function getDate(dateStr) {
var arr = dateStr.split('.');
return new Date(arr[2], arr[1], arr[0]);
}
var start = getDate("04.11.2016");
var end = getDate("19.11.2016");
var timeDiff = Math.abs(end.getTime() - start.getTime());
var diffDays = Math.ceil(timeDiff / (1000 * 60 * 60 * 24))
console.log('Number of days: ' + diffDays);
In order to use this code to create a Custom JavaScript Variable in Google Tag Manager, you can modify the above code or the one which you choose to be inside a function - reference.