I have a date variable being set on my page like this:
startDate = "03/28/2017";
How can I check if that date is 7 or less days before today's date?
It will need to be used in a conditional if statement.
You can try using moment.js,
var a = moment([2007, 0, 29]);
var b = moment([2007, 0, 28]);
a.diff(b) // 86400000
or even better, it has an inbuilt method, which says after how many days.
moment([2007, 0, 29]).toNow(); // in 4 years
and if you want to use old plain javascript :
var date1 = new Date("3/30/2017");
var date2 = new Date("3/23/2017");
var timeDiff = Math.abs(date2.getTime() - date1.getTime());
var diffDays = Math.ceil(timeDiff / (1000 * 3600 * 24));
If you want to compare with today
var date1 = new Date("3/23/2017")
var date2 = new Date();
Related
What's the most concise, performant way to get in Javascript the minutes remaining between now, and the upcoming day at 01:00 (am)?
Then, once the current time is after 01:00, I start calculating the difference to the next.
in javascript, a specified date can be provided like this
var date1 = new Date('June 6, 2019 03:24:00');
or it can be specified like this
var date2 = new Date('2019-6-6T03:24:00');
javascript can natively subtract 2 dates
console.log(date1 - date2);
//expected 0;
using this method will output the difference in the dates in milliseconds,
to get minutes you'll want to divide the value by 60000;
so
var futureTime = new Date('2019-06-06T07:24:00');
//there must be a 0 infront of 1 digit numbers or it is an invalid date
var now = new Date();
var difference = (futureTime - now) / 60000;
//get minutes by dividing by 60000
//doing Date() with no arguments returns the current date
read about the javascript Date object here for more information
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date
let now = new Date();
let next1am = new Date();
next1am.setHours(1, 0, 0, 0); // same as now, but at 01:00:00.000
if (next1am < now) next1am.setDate(next1am.getDate() + 1); // bump date if past
let millisecondDiff = next1am - now;
let minuteDiff = Math.floor(millisecondDiff / 1000 / 60);
you can you moment.js here
var current = new Date()
var end = new Date(start.getTime() + 3600*60)// end time to calculate diff
var minDiff = end - start; // in millisec
You can calculate by pure JavaScript:
let today = new Date();
let [y,M,d,h,m,s] = '2019-06-04 05:00:11'.split(/[- :]/);
let yourDate = new Date(y,parseInt(M)-1,d,h,parseInt(m)+30,s);
let diffMs = (yourDate - today);
let diffDays = Math.floor(diffMs / 86400000); // days
let diffHrs = Math.floor((diffMs % 86400000) / 3600000); // hours
let diffMins = (diffDays * 24 * 60)
+ (diffHrs *60)
+ Math.round(((diffMs % 86400000) % 3600000) / 60000); // The overall result
// in minutes
In, addition avoid using the built–in parser for any non–standard format, e.g. in Safari new Date("2019-04-22 05:00:11") returns an invalid date. You really shouldn't even use if for standardized formats as you will still get unexpected results for some formats. Why does Date.parse give incorrect results?
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.
I have the current script. var date 2 needs to automatically grab the current date and then do the calculation. I have tried many things with no luck, please help.
<script>
// Here are the two dates to compare
var date1 = '2015-09-08';
var date2 = '2015-12-13';
// 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;
// in weeks :)
var timeDifferenceInWeeks = timeDifferenceInHours / 24/7;
document.write(Math.ceil(timeDifferenceInWeeks));
</script>
You can use new Date() to get current date. please refer snippet.
<script>
// Here are the two dates to compare
var date1 = '2015-09-08';
var date2 = '2015-12-13';
// 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]-1, date1[2]);
date2 = new Date(date2[0], date2[1]-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());
date2_unixtime = parseInt(date2.getTime());
date3_unixtime = parseInt((new Date()).getTime());
// This is the calculated difference in seconds
var timeDifference = date2_unixtime - date1_unixtime;
var timeDifferenceInWeeks1 = timeDifference / (1000*60*60*24*7);
var timeDifferenceInWeeks2 = (date3_unixtime - date2_unixtime) / (1000*60*60*24*7);
document.write(Math.ceil(timeDifferenceInWeeks1)+'--'+Math.ceil(timeDifferenceInWeeks2));
</script>
just use
var date2 = new Date();
now the date2 holds the current date and time from your machine.
I changed to a php code and the following is what I got to work.
<?
$strtDate = '2015-09-08';
$endDate = date('Y-m-d');
//$endDate = 'new Date();';
$startDateWeekCnt = round(floor( date('d',strtotime($strtDate)) / 7)) ;
// echo $startDateWeekCnt ."\n";
$endDateWeekCnt = round(ceil( date('d',strtotime($endDate)) / 7)) ;
//echo $endDateWeekCnt. "\n";
$datediff = strtotime(date('Y-m',strtotime($endDate))."-01") - strtotime(date('Y-m',strtotime($strtDate))."-01");
$totalnoOfWeek = round(floor($datediff/(60*60*24)) / 7) + $endDateWeekCnt - $startDateWeekCnt ;
echo $totalnoOfWeek ."\n";
?>
I want to get the difference of of these dates.
e.g
var current_date = new Date();
var date_from_database = "2013/06/10 15:00:00";
var difference = data_from_datebase - current_date;
// so the result should be: 7
I want to get how many days left buy subtracting the current day on specific day like the example above. How can I do this on javascript?
Thanks in advance!
The following might work:
var oneDay = 24*60*60*1000; // hours*minutes*seconds*milliseconds
var firstDate = new Date(2008,01,12);
var secondDate = new Date(2008,01,22);
var diffDays = Math.round(Math.abs((firstDate.getTime() - secondDate.getTime())/(oneDay)));
var date_from_database = new Date("2013/06/10 15:00:00");
var date1= new Date();
var date_diff = Math.abs(date2.getTime() - date_from_database .getTime()/86400000);
In order to compare it with the current day:
var firstDate = new Date(2008,01,12);
var secondDate = new Date();
var timeDiff = Math.abs(firstDate.getTime() - secondDate.getTime());
var diffDays = Math.ceil(timeDiff / (1000 * 3600 * 24));
alert(diffDays);
http://jsfiddle.net/imac/TEjqX/
You will have to modify the date you receive from the database to addapt it to the needed parameter for date().
You can take a look at this answer for more info.
Javascript could be very pesky in processing the datetime variables.
Do not reinvent the wheel. I often use the datejs library.
In particular, the time.js file features the TimeSpan() function that processes datetime differences.
References:
date.js main page
date.js # google code
time.js page
I realize that the current timestamp can be generated with the following...
var timestamp = Math.round((new Date()).getTime() / 1000);
What I'd like is the timestamp at the beginning of the current day. For example the current timestamp is roughly 1314297250, what I'd like to be able to generate is 1314230400 which is the beginning of today August 25th 2011.
Thanks for your help.
var now = new Date();
var startOfDay = new Date(now.getFullYear(), now.getMonth(), now.getDate());
var timestamp = startOfDay / 1000;
Well, the cleanest and fastest way to do this is with:
long timestamp = 1314297250;
long beginOfDay = timestamp - (timestamp % 86400);
where 86400 is the number of seconds in one day
var now = new Date; // now
now.setHours(0); // set hours to 0
now.setMinutes(0); // set minutes to 0
now.setSeconds(0); // set seconds to 0
var startOfDay = Math.floor(now / 1000); // divide by 1000, truncate milliseconds
var d = new Date();
d.setHours(0);
d.setMinutes(0);
d.setSeconds(0);
d.setMilliseconds(0);
var t = d / 1000;
Alternatively you could subtract the modulo of a days length in miliseconds e.g.
var day = 24*60*60*1000;
var start_of_today = Date.now() - Date.now() % day;
Luis Fontes' solution returns UTC time so it can be 1 hour (daylight saving time) different from setHours solution.
var d = new Date();
var t = d - (d % 86400000);
Simplified version of examples above (local time).
var d = new Date();
d.setHours(0,0,0,0);
var t = d / 1000;
Here you can find some performance tests: http://jsperf.com/calc-start-of-day
Another alternative for getting the beginning of the day is the following:
var now = new Date();
var beginningOfDay = new Date(now.getTime() -
now.getHours() * 60 * 60 * 1000 -
now.getMinutes() * 60 * 1000 -
now.getSeconds() * 1000 -
now.getMilliseconds());
var yoursystemday = new Date(new Date().getTime()-(120000*60+new Date().getTimezoneOffset()*60000));
yoursystemday = new Date();
var current_time_stamp = Math.round(yoursystemday.getTime()/1000);
For any date it's easy to get Timestamps of start/end of the date using ISO String of the date ('yyyy-mm-dd'):
var dateString = '2017-07-13';
var startDateTS = new Date(`${dateString}T00:00:00.000Z`).valueOf();
var endDateTS = new Date(`${dateString}T23:59:59.999Z`).valueOf();
To get ISO String of today you would use (new Date()).toISOString().substring(0, 10)
So to get TS for today:
var dateString = (new Date()).toISOString().substring(0, 10);
var startDateTS = new Date(`${dateString}T00:00:00.000Z`).valueOf();
var endDateTS = new Date(`${dateString}T23:59:59.999Z`).valueOf();
var now = new Date();
var startOfDay = new Date(now.getFullYear(), now.getMonth(), now.getDate());
var timestamp = startOfDay.getTime() / 1000;