I have my map where I display some incidents over time. Until now I used the data which is filtered like this
dpG = d3.time.format("%d.%m.%Y").parse;
dpS = d3.time.format("%Y-%m-%d").parse;
var minDate = dpG("01.01.2015");
var maxDate = dpG("31.12.2015");
var secondsInDay = 60 * 60 * 24;
d3.select('#slider3').call(d3.slider()
.axis(true).min(minDate).max(maxDate)
.on("slide", function(evt, value) {
newDataG = site_dataG.features.filter(function(d){
var date = (dpG(d.properties.date).getTime() === new Date(value).getTime());
// console.log(date)
//console.log(new Date(value));
console.log(dpG(d.properties.date));
return(date);
});
// newDataS = site_dataS.features.filter(function(d){
// return dpS(d.properties.Date) < new Date(value);
// });
// console.log(newDataG);
// console.log("New set size ", newDataG.length);
displaySitesG(newDataG);
// displaySitesS(newDataS);
})
);
But now I tried to filter for only one day and not for all days until new Date(value)
So I tried something like this
newDataG = site_dataG.features.filter(function(d){
var date = dpG(d.properties.date) == new Date(value);
// console.log(date)
//console.log(new Date(value));
return(date);
});
Which turned out to be not working at all.
And something like this displays all data at once.
var date = new Date(value);
The other files is github repo if you need to see
EDIT2:
date1 = Math.round(dpG(d.properties.date).getTime() / (1000*60*60*24));
date2 = Math.round(new Date(value).getTime() / (1000*60*60*24));
console.log(date1);
console.log(date2)
gives me this
Checking for equality directly doesn't work with date objects:
var d1 = new Date();
var d2 = new Date(d1);
console.log(d1 == d2); // false!
Instead, you need to use th date.getTime() operator if you want to use the ==, !=, ===, and !== operators:
var d1 = new Date();
var d2 = new Date(d1);
d1.getTime() === d2.getTime(); // true
So, try this instead: (edited to fix error)
var date = (dpG(d.properties.date).getTime() === new Date(value).getTime());
Note that this will only work if dpG(thing) returns a Date object.
I used moment.js to make the UnixTimeStamp even
here is the code snippet which helped
d3.select('#slider3').call(d3.slider()
.axis(true).min(minDate).max(maxDate)
.on("slide", function(evt, value) {
sliderDate = moment(value,"x").utc().format("YYYY-MM-DD");
newDataS = site_dataS.features.filter(function(d){
//sliderDate = moment(value,"x").utc().format("YYYY-MM-DD");
dataDate = d.properties.Date;
//dataDateStampS = moment(dataDate).unix();
if (dataDate == sliderDate) {
return dpS(dataDate);
}
});
displaySitesS(newDataS);
})
);
Related
var startDateTime = '15.04.2019 00:15';
var endDateTime = '17.05.2019 18:35';
var checkDateTime = '16.04.2019 13:15';
function(checkDateTime, startDateTime, endDateTime) {
// need codes to return true or false,.
// check "checkDateTime" is between "startDateTime" to "endDateTime"
}
Try this code:
var startDateTime = getDate('15.04.2019 00:15');
var endDateTime = getDate('17.05.2019 18:35');
var checkDateTime = getDate('16.04.2019 13:15');
function isBetween(checkDateTime, startDateTime, endDateTime) {
return (checkDateTime >= startDateTime && checkDateTime <= endDateTime);
}
function toDate(str){
var [ dd, MM, yyyy, hh, mm ] = str.split(/[. :]/g);
return new Date(`${MM}/${dd}/${yyyy} ${hh}:${mm}`);
}
console.log(isBetween(checkDate,startDate,endDate));
To compare it one time falls between a time interval on the same day use: -
var startTime = "00:35";
var endTime = "18:15";
var checkTime = "13:00";
function getMinutes(timeString){
let [hh, mm] = timeString.split(":");
return parseInt(hh)*60 + parseInt(mm);
}
function isTimeBetween(checkTime,startTime,endTime){
checkTime = getMinutes(checkTime);
return (checkTime >= getMinutes(startTime) && checkTime <= getMinutes(endTime));
}
console.log(isTimeBetween(checkTime,startTime,endTime));
You can use new Date().getTime() to get the number of milliseconds since the Unix Epoch. So that you can compared the date/time with the result from this function. You can do sth like that:
return new Date(startDateTime).getTime() <= new Date(checkDateTime).getTime() <= new Date(endDateTime).getTime();
Check this out:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/getTime
I would suggest to check if your checkDateTime is greater than your startDateTime and less then endDateTime.
function checkDateTime(checkDateTime, startDateTime, endDateTime) {
return (new Date(startDateTime) >= new Date(checkDateTime))
&& (new Date(checkDateTime) <= new Date(endDateTime));
}
Here is yet another option which adds the method directly to the Date prototype:
var startDateTime = new Date('04/15/2019 00:15');
var endDateTime = new Date('05/17/2019 18:35');
var checkDateTime = new Date('04/16/2019 13:15');
var outOfRangeDate_EARLY = new Date('01/16/2019 13:15');
var outOfRangeDate_LATE = new Date('06/16/2019 13:15');
Date.prototype.inRange = function(startDate, endDate){
var this_ms = this.getTime();
return ( this_ms >= startDate.getTime() && this_ms <= endDate.getTime() )
}
/* Tests */
console.log('expected: true', 'actual:', checkDateTime.inRange(startDateTime, endDateTime))
console.log('expected: false', 'actual:', outOfRangeDate_EARLY.inRange(startDateTime, endDateTime))
console.log('expected: false', 'actual:', outOfRangeDate_LATE.inRange(startDateTime, endDateTime))
This way, with any date you have var someDate, you can just call someDate.inRange(startDate, endDate). Sometimes, however, messing with the native prototypes can come back to haunt you if not careful. If so, having a separate function as answered by the others is very good.
Lastly, it's very important that the date strings are formatted properly before creating the Date objects, otherwise you'll encounter Invalid Date a lot. I hope this helps.
unixTimeStamp1 = 1532676600;
unixTimeStamp2 = 1532680500;
I have to compare the above two unix time stamp values and return true if both the dates are same.
Compare the toDateString of each date:
const getDateStr = secs => {
const d = new Date(secs * 1000);
return d.toDateString();
};
const d1 = getDateStr(1532676600);
const d2 = getDateStr(1532680500);
console.log(d1);
console.log(d2);
console.log(d1 === d2);
var unixTimeStamp1 = 1532676600;
var unixTimeStamp2 = 1532680500;
var date1 = new Date(unixTimeStamp1 * 1000);
var date2 = new Date(unixTimeStamp2 * 1000);
if ((date1.getFullYear() === date2.getFullYear()) &&
(date1.getMonth() === date2.getMonth()) &&
(date1.getDate() === date2.getDate())
) {
console.log("same");
}
You need to get the full date value from that timestamp using new Date().toDateString(). Then compare it. Also it is a unix timestamp so you need to convert that to JavaScript timestamp first using unixTimeStamp * 1000
var unixTimeStamp1 = 1532676600;
var unixTimeStamp2 = 1532680500;
function checkDate(unixTimeStamp1, unixTimeStamp2){
var date1 = new Date(unixTimeStamp1 * 1000).toDateString();
var date2 = new Date(unixTimeStamp2 * 1000).toDateString();
return date1 === date2;
}
console.log(checkDate(unixTimeStamp1, unixTimeStamp2));
unixTimeStamp1 = 1532156518;
unixTimeStamp2 = 1533839400;
console.log(checkDate(unixTimeStamp1, unixTimeStamp2));
But if you just want to get the date for the day ignoring the year and month then you can use getDate():
var unixTimeStamp1 = 1532676600;
var unixTimeStamp2 = 1532680500;
function checkDate(unixTimeStamp1, unixTimeStamp2){
var date1 = new Date(unixTimeStamp1 * 1000).getDate();
var date2 = new Date(unixTimeStamp2 * 1000).getDate();
return date1 === date2;
}
console.log(checkDate(unixTimeStamp1, unixTimeStamp2));
unixTimeStamp1 = 1532156518;
unixTimeStamp2 = 1533839400;
console.log(checkDate(unixTimeStamp1, unixTimeStamp2));
I'm using cleandersonlobo:date-picker-materialize package to input the date and I want to display an alert("expired") if the input date is less than the current date.
var $strDate = $(".pmt-date").val();
var $dtDate = $.datepicker.parseDate("mm/dd/yy", $strDate);
var $strToday = $.datepicker.formatDate('mm/dd/yy', new Date());
var $tDate = $.datepicker.parseDate('mm/dd/yy', $strToday);
if ($dtDate < new Date()) {
$('#myModal1').modal('hide');
alert("Job expired");
}
Try following code,
var $strDate = $(".pmt-date").val();
var $dtDate = $.datepicker.parseDate("mm/dd/yy", $strDate);
var $strToday = $.datepicker.formatDate('mm/dd/yy', new Date());
var $tDate = $.datepicker.parseDate('mm/dd/yy', $strToday);
if ($dtDate < $strToday ) {
$('#myModal1').modal('hide');
alert("Job expired");
}
A toMidnight function that sets the time of a date to midnight and by doing so removes time as a factor for your comparison:
function toMidnight(date) {
var midnight = arguments.length > 0 ? new Date(date) : new Date();
midnight.setHours(0);
midnight.setMinutes(0);
midnight.setSeconds(0);
midnight.setMilliseconds(0);
return midnight;
}
Then you can compare your date like this:
toMidnight($dtDate) < toMidnight()
I have a form with a simple input type. I'm trying to define a function to check if the date is no more than 6 months older compared to date provided by the input type.
I know i have to convert the String provided by the input in a Date object to make this comparison and then work on get methods of Date object, but i can't figure out how to do this.
Current code:
$scope.compareDates = function(d1) {
d1 = new Date(d1); //convert String into date Object
var d = new Date(); // today date
d.setYear(d.getFullYear());
d.setMonth(d.getMonth() - 6);
if(d1 > d ) {
console.log("ok");
} else {
console.log("error");
}
}
EDIT:
I'm sorry, i forgot to add my input. Here it is:
<input class="form-control" type="text" placeholder="gg/mm/aaaa" ng-model="sStartDate" ng-change="change()">
Angular Controller:
$scope.sStartDate = '';
$scope.change = function(){
var startDt = $scope.sStartDate;
$scope.compareDates(startDt);
}
If I am reading your code correctly, your date format is days/month/year which is not valid format. You need to swap the month and days.
var parts = d1.split(),
dateStr = parts[1] + "/" + parts[0] + "/" parts[2],
d1 = new Date(d1),
d = new Date();
d.setMonth(d.getMonth() - 6);
if(d1 > d ) {
console.log("ok");
} else {
console.log("error");
}
What's about using d.getTime()?
$scope.compareDates = function(d1){
d1 = new Date(d1); //convert String into date Object
var d = new Date(); // today date
d.setMonth(d.getMonth() - 6);
if(d1.getTime() > d.getTime() ) {
console.log("ok");
} else {
console.log("error");
}
}
Regards.
I used momentjs for this in our app. It makes this process very easy and smooth.
// is6MonthsOld will be a boolean value
var is6MonthsOld = moment(d1).isBefore(moment().subtract(6, 'months'));
If you are comparing dates and not time, make sure to reset time in your date object using d1.setHours(0,0,0,0).
When you do new Date(), output is a datetime object, but when you do new Date(2015,6,19), only date is assigned and time is set to 00:00:00.
Following code depicts the same:
function compareDates(d1,d2){
return +d2 > +d1;
}
function compareDatesWithHoursReset(d1,d2){
d1.setHours(0,0,0,0);
d2.setHours(0,0,0,0);
return +d2 > +d1;
}
function main(){
var d1 = new Date();
var d2 = new Date(2015, 6, 19);
d1.setMonth(d1.getMonth() - 6)
console.log(d1);
console.log(d2);
console.log(compareDates(d2,d1))
console.log(compareDatesWithHoursReset(d2,d1))
}
main();
Hi i am trying to do a IF statement which allows the current date to be compared to the input date.. if the input date is below the current date it will be false.
I have got the date passing through my variable but it only stores the number so for example it compares day 9 to another day, which is not very reliable. I want the variable to take in the month and the year as well, meaning it can compare the ENTIRE DATE.
If there is a better way let me know.
Here is my code
if (this.element.find('#visitdate').length > 0) {
var dateParts = $('#visitdate').val().split('/');
var check = new Date(dateParts[2], dateParts[1], dateParts[0], 0,0,0,0).getDate();
var today = new Date().getDate;
if (check < today) {
_errMsg = "Please enter a furture visit date";
return false;
} else {
return true;
}
}
Your line for today's date contains an error:
var today = new Date().getDate;
should be
var today = new Date().getDate();
format as mm/dd/yyyy
var from = '08/19/2013 00:00'
var to = '08/12/2013 00:00 '
var today = new Date().getDate();
function isFromBiggerThanTo(dtmfrom, dtmto){
var from = new Date(dtmfrom).getTime();
var to = new Date(dtmto).getTime() ;
return from >= to ;
}
or using below
var x = new Date('2013-05-23');
var y = new Date('2013-05-23');
and compare
You can try this - it's working fine in my project -
Step 1
First Create javascript function as below.
Date.prototype.DaysBetween = function () {
var intMilDay = 24 * 60 * 60 * 1000;
var intMilDif = arguments[0] - this;
var intDays = Math.floor(intMilDif / intMilDay);
if (intDays.toLocaleString() == "NaN") {
return 0;
}
else {
return intDays + 1;
}
}
Step 2
-
var check = new Date(dateParts[2], dateParts[1], dateParts[0], 0,0,0,0).getDate();
var today = new Date().getDate;
var dateDiff = check .DaysBetween(today);
// it will return integer value (difference between two dates )
if(dateDiff > 0 ){ alert('Your message.......');}
You can have this much easier.
You dont need to check with getDate() property you can just compare 2 dates.
And also is not needed to initialize with hours, minutes and seconds the Date, you only need year, month and date.
Here you have your example simplified
var dateParts = $('#visitdate').val().split('/');
var check = new Date(dateParts[2], dateParts[1], dateParts[0]);
var today = new Date();
if (check < today) {
return false;
} else {
return true;
}
http://jsfiddle.net/wns3LkLv/
Try this:
var user="09/09/2014/5/30";
var arrdt= user.split("/");
var userdt = new Date(arrdt[2], arrdt[1] - 1, arrdt[0],arrdt[3],arrdt[4]);
var currdt = new Date();
if (userdt < currdt) {
alert("userdate is before current date"); //do something
}else{
alert("userdate is after current date"); //do something
}
Thanks for all your answers guys i have fixed it.
I used the getTime function instead of getDate.
Then the check variable had to have a -1 assigned to the month as it was going 1 month to high.
var check = new Date(dateParts[2], dateParts[1]-1, dateParts[0], 0,0,0,0).getTime();
Cheers