Why does two JS date Objects instantianted differently? - javascript

I'd like to enable/disable a button based on a datepicker, and I have a setup for a check like this:
public dateChanged = false;
public availableFromDate: Date;
public availableToDate: Date;
initDatepickers() {
const currentDay = new Date();
this.availableFromDate = currentDay;
this.availableToDate = currentDay;
}
private dateCheck() {
if ((this.availableFromDate > this.availableToDate) || (this.availableFromDate === this.availableToDate)) {
this.dateChanged = false;
} else {
this.dateChanged = true;
}
console.log(this.dateChanged);
console.log(`Available from - ${this.availableFromDate}`);
console.log(`Available to - ${this.availableToDate}`);
}
The check works good upwards, and enables the button when from date is lower, however!
If you log the values to the console be button is disabled because the init value is false, not because the check works.
The two date objects are initialized differently (console.log dump):
true
clinics-upload-documents.component.ts:73 Available from - Fri Feb 22 2019 00:00:00 GMT+0100 (Central European Standard Time)
clinics-upload-documents.component.ts:74 Available to - Fri Feb 22 2019 10:52:31 GMT+0100 (Central European Standard Time)
It's never going to be false because the first date obj is # 0:00:00 however the 2nd is tied to current local time.
these are used to manipulate the dates:
onFromChange(fromDate) {
const dateType = 'from';
this.setDateValues(fromDate, dateType);
}
onToChange(toDate) {
const dateType = 'to';
this.setDateValues(toDate, dateType);
}
private setDateValues(date: Date, dateType: string) {
dateType === 'from' ? this.availableFromDate = new Date(date) : this.availableToDate = new Date(date);
this.dateCheck();
}
What am I missing so badly?

Change this:
const currentDay = new Date();
this.availableFromDate = currentDay;
this.availableToDate = currentDay;
To this:
const currentDay = new Date();
currentDay.setHours(0, 0, 0, 0);
this.availableFromDate = new Date(currentDay);
this.availableToDate = new Date(currentDay);
This will zero out the time portion and make date comparison straight forward.
Next, change this:
if (
(this.availableFromDate > this.availableToDate) ||
(this.availableFromDate === this.availableToDate)
)
To this (assuming that you want to check greater than or equal to):
if (this.availableFromDate >= this.availableToDate)
You cannot compare two dates with === although you can compare them using < <= >= >.

It looks like the Date objects that come in from your date picker via onFromChange/onToChange are pure dates (they are all at midnight), while the date objects that you create with Date() will have the current time included. The js Date class should really have been called DateTime. The mismatched times will cause the === comparison to fail.
Try using something like this to set availableFromDate and availableToDate in your initDatepickers function:
private getCurrentDate() {
const date = new Date();
date.setHours(0);
date.setMinutes(0);
date.setSeconds(0);
date.setMilliseconds(0);
}
EDIT: Nevermind, the === will still fail if you do this, because Date is an object, so === checks for reference equality. Two Date objects can hold the same underlying date/time values, but they are still considered to be separate objects. Things like numbers, however, are value types, so === will tell you if the two values are equal. E.g:
5 === 5; // True, because pure numbers are value types
const number1 = { number: 5 }; // This is an object, so it is a reference type. Dates are also objects.
const number2 = { number: 5 }; // Another reference type
number1 === number2; // False, because although number1 and number2 hold the same values, they are still distinct objects.
See Salman's answer for a proper solution.

Related

Replace specific date with text using Javascript

New to javascript here, and am trying to replace a specific event dates with text. Events dates are in the format #F #d, and I'd like to instead show "Christmas" if #F #d = December 25. Thanks in advance.
const eventdate = #F #d;
let dateswap;
if (eventdate == 'December 25') {
dateswap = "Christmas";
}
document.innerHTML = dateswap;
You can use an if statement to change the variable's value if it is equal to a specific date.
let date = 'December 25';
if (date === 'December 25') {
date = 'Christmas';
}
console.log(date); // value is now "Christmas"
Generally in the future it's always good to show your effort, but welcome to SO here's a freebie! :)
// Let's pretend this is what's supplying your date.
const date = new Date(),
christmasDay = new Date('December 25, 2021 00:00:01'),
output = document.getElementById('output-example'),
christmasMessage = 'IT IS CHRISTMAS! HO HO HO!';
// Now let's find out if it's christmas.
// First we see if month == 11 (because month works as array and starts count at 0 not 1)
// Then we check to see if the current day is the 25th with getDate()
// If the date matches we display a special christmas greeting, if not then something else.
// To see it work change "date" for .getMonth() and .getDate() below to "christmasDay"
// This way you can simulate the christmas day date to see the change.
isChristmas = (d) => {
return d.getMonth() == 11 && d.getDate() == 25;
}
// if you wanted an if example
if (isChristmas(date)) {
output.innerHTML=`<h1 style="color:red">${christmasMessage} - ${date.toLocaleDateString('en-US')}</h1>`;
} else {
output.innerHTML=`<h1 style="color:blue">Sorry, not yet christmas :( - ${date.toLocaleDateString('en-US')}</h1>`;
}
// --------------------------------------------------
// Or just set a function to return accordingly
isTodayChristmas = (d) => {
// with a ternary example
return isChristmas(d) ? christmasMessage : d;
}
// We'll use christmas day var to ensure we're sending the christmas date for this example.
console.log(isTodayChristmas(christmasDay));
<div id="output-example"></div>

How do I subtract two dates?

I have a date stored in a database as a string. It looks like this:
Tue Aug 23 2016 00:00:00 GMT-0500 (CDT)
I basically want to tell if today's date is before or after the date in the database.
The code below should sort of explain what I want. The problem is that after the difference variable doesn't return a number variable, which is what I need.
var expire = value.vaccines;
var today = new Date();
var difference = today-expire;
if(difference <= 0){
$(element).css({"color": "#0040ff"});
}
Any ideas on how to subtract these two dates and get a number value?
Assuming both your objects are Date
Although you only require the returned value in milliseconds, I've added the extra step of formatting the value.
Math.floor((today - expire) / (1000*60*60*24))
Taken from Here
You can just you can calculate the difference between the two Date objects and get the absolute value with Math.abs():
var today = new Date(),
expire = value.vaccines,
difference = Math.abs(today - expire); // difference in milliseconds
if (difference <= 0) {
$(element).css({
"color": "#0040ff"
});
}
Check that expire is a valid Date object.

Date Validation - how to work around Javascript's auto-correcting of dates?

I want to validate dates by Javascript and found this nice answer:
https://stackoverflow.com/a/1353711/3391783
but when i try to use it to validate dates, it seems like Javascript is auto-correcting my date by taking the closest valid date. so this will return true even though 2014-11-31 is not a valid date (Javascript months start at 0, so 10 equals November):
function isValidDate(d) {
if ( Object.prototype.toString.call(d) !== "[object Date]" )
return false;
return !isNaN(d.getTime());
}
var test_date = new Date(2014, 10, 31);
console.log( test_date );
console.log( isValidDate(test_date) );
seems like creating the Date is automatically switching it to 2014-12-01 which is a correct date.
but I would like to be able to validate user input without changing it.
So how can i create an invalid new Date() in Javascript?
Or is there a much simpler way to do this?
You can use the auto-correction in the Date object to validate the date. Just check the input against what you have in the Date object:
var y = 2014, m = 10, d = 31;
var test_date = new Date(y, m, d);
var valid =
test_date.getFullYear() == y &&
test_date.getMonth() == m &&
test_date.getDate() == d;
document.write(valid);
When it comes to handling dates in JavaScript, I'm a big fan of Moment.js. As you can see here, they do a good job of validating dates: http://momentjs.com/docs/#/parsing/is-valid/
new Date(2013, 25, 14).toString(); // "Sat Feb 14 2015 00:00:00 GMT-0500 (EST)"
moment([2015, 25, 35]).format(); // 'Invalid date'
Here's a function I wrote a while back that demonstrates Guffa's solution.
function isValidDate(checkDate) {
if(!/\d\d\/\d\d\/\d\d\d\d/.test(checkDate)) {
return false; // checkDate is not formatted as ##/##/####
} else {
// split checkDate into three pieces
var strMM = checkDate.split('/')[0];
var strDD = checkDate.split('/')[1];
var strYYYY = checkDate.split('/')[2];
// create new Date() object from split pieces
var strDateCheck = new Date(strYYYY,(strMM - 1),strDD);
// evaluate each piece of resulting date object against each corresponding piece of checkDate
if(((strDateCheck.getMonth() + 1) == strMM) && (strDateCheck.getDate() == strDD) && (strDateCheck.getFullYear() == strYYYY)) {
/* if you wish, add additional validation constraints here */
return true; // all three pieces match exactly
} else {
return false; // at least one piece did not match
}
}
}

Compare dates javascript

I need to validate different date's with some javascript(jquery).
I have a textbox with, the inputmask from jquery (http://plugins.jquery.com/plugin-tags/inputmask). The mask that i use is "d/m/y".
Now i have set up a CustomValidator function to validate the date.
I need 2 functions. One to check if the given date is greater then 18 years ago. You must be older then 18 year.
One function to check if the date is not in the future. It can only in the past.
The function are like
function OlderThen18(source, args) {
}
function DateInThePast(source, args) {
}
As you know the value you get back with args.Value is 27/12/1987 .
But how can i check this date in the functions? So that i can set args.IsValid to True or False.
I tried to parse the string(27/12/1987) that i get back from the masked textbox to a date but i get always a value back like 27/12/1988.
So how could I check the given dates with the other dates?
The simple way is to add 18 years to the supplied date and see if the result is today or earlier, e.g.:
// Input date as d/m/y or date object
// Return true/false if d is 18 years or more ago
function isOver18(d) {
var t;
var now = new Date();
// Set hours, mins, secs to zero
now.setHours(0,0,0);
// Deal with string input
if (typeof d == 'string') {
t = d.split('/');
d = new Date(t[2] + '/' + t[1] + '/' + t[0]);
}
// Add 18 years to date, check if on or before today
if (d.setYear && d.getFullYear) {
d.setYear(d.getFullYear() + 18);
}
return d <= now;
}
// For 27/4/2011
isOver18('27/4/2011'); // true
isOver18('26/4/2011'); // true
isOver18('28/4/2011'); // false
try this to start:
var d = new Date(myDate);
var now = new Date();
if ((now.getFullYear() - d.getFullYear()) < 18) {
//do stuff
}
The javascript date object is quite flexible and can handle many date strings.
You can compare two Date objects or use the Date interface methods, such as getSeconds() of getFullYear() in order to deduce useful data regarding the date.
See Date object reference formore details.
You'll need to construct, modify and compare Date objects - something like this:
// str should already be in dd/mm/yyyy format
function parseDate(str) {
var a = str.split('/');
return new Date(parseInt(a[2], 10), // year
parseInt(a[1], 10) - 1, // month, should be 0-11
parseInt(a[0], 10)); // day
}
// returns a date object for today (at midnight)
function today() {
var date = new Date();
date.setHours(0, 0, 0);
return date;
}
function DateInThePast(str) {
// date objects can be compared like numbers
// for equality (==) you'll need to compare the value of date.getTime()
return parseDate(str) < today();
}
function OlderThan18(str) {
// left as an exercise for the reader :-)
}

Date Parsing and Validation in JavaScript

How would I achieve the pseudo-code below in JavaScript? I want to include the date check in the second code excerpt, where txtDate is for the BilledDate.
If ABS(billeddate – getdate) > 31 then yesno “The date you have entered is more than a month from today, Are you sure the date is correct,”.
if (txtDate && txtDate.value == "")
{
txtDate.focus();
alert("Please enter a date in the 'Date' field.")
return false;
}
Generally speaking you work with Date-objects in javascript, and these should be constructed with the following syntax:
var myDate = new Date(yearno, monthno-1, dayno);
//you could put hour, minute, second and milliseconds in this too
Beware, the month-part is an index, so january is 0, february is 1 and december is 11 !-)
Then you can pull out anything you want, the .getTime() thing returns number of milliseconds since start of Unix-age, 1/1 1970 00:00, så this value you could subtract and then look if that value is greater than what you want:
//today (right now !-) can be constructed by an empty constructor
var today = new Date();
var olddate = new Date(2008,9,2);
var diff = today.getTime() - olddate.getTime();
var diffInDays = diff/(1000*60*60*24);//24 hours of 60 minutes of 60 second of 1000 milliseconds
alert(diffInDays);
This will return a decimal number, so probably you'll want to look at the integer-value:
alert(Math.floor(diffInDays));
To get the date difference in days in plain JavaScript, you can do it like this:
var billeddate = Date.parse("2008/10/27");
var getdate = Date.parse("2008/09/25");
var differenceInDays = (billeddate - getdate)/(1000*60*60*24)
However if you want to get more control in your date manipulation I suggest you to use a date library, I like DateJS, it's really good to parse and manipulate dates in many formats, and it's really syntactic sugar:
// What date is next thrusday?
Date.today().next().thursday();
//or
Date.parse('next thursday');
// Add 3 days to Today
Date.today().add(3).days();
// Is today Friday?
Date.today().is().friday();
// Number fun
(3).days().ago();
You can use this to check for valid date
function IsDate(testValue) {
var returnValue = false;
var testDate;
try {
testDate = new Date(testValue);
if (!isNaN(testDate)) {
returnValue = true;
}
else {
returnValue = false;
}
}
catch (e) {
returnValue = false;
}
return returnValue;
}
And this is how you can manipulate JS dates. You basically create a date object of now (getDate), add 31 days and compare it to the date entered
function IsMoreThan31Days(dateToTest) {
if(IsDate(futureDate)) {
var futureDateObj = new Date();
var enteredDateObj = new Date(dateToTest);
futureDateObj.setDate(futureDateObj.getDate() + 31); //sets to 31 days from now.
//adds hours and minutes to dateToTest so that the test for 31 days is more accurate.
enteredDateObj.setHours(futureDateObj.getHours());
enteredDateObj.setMinutes(futureDateObj.getMinutes() + 1);
if(enteredDateObj >= futureDateObj) {
return true;
}
else {
return false;
}
}
}
Hello and good day for everyone
You can try Refular Expressions to parse and validate a date format
here is an URL yoy can watch some samples and how to use
http://www.javascriptkit.com/jsref/regexp.shtml
A very very simple pattern would be: \d{2}/\d{2}/\d{4}
for MM/dd/yyyy or dd/MM/yyyy
With no more....
bye bye

Categories

Resources