Comparing 2 strings from HTML file - Angular - html

I am using angular 7 and I would like to know how to compare two strings. In this case, each of my strings simulates one date, let's say "2019-12-26" and "2018-12-26".
In Javascript is pretty simple to compare them since I just need to use the operators:
console.log(today > "2018-12-06");
It is working how I supposed it was gonna work. It basically returns true. Nevertheless, I am trying to do exactly the same from my HTML file
<div *ngIf="today > example.endDate">
being today and 'example.endDate' two strings containing exactly the same strings that I used for the Javascript example, but it does not show any of them.
Is there any other way to make this comparison?
Regards,
Mario
UPDATE
I have had a second look at the problem and it seems that the comparison is not a problem, but the way of getting the variable is.
I get a variable in ngOnInit().
ngOnInit() {
this.getCurrentDate();
}
//Get current date
getCurrentDate() {
let aux = new Date();
//2 characteres
let dd = String(aux.getDate()).padStart(2, "0");
let mm = String(aux.getMonth() + 1).padStart(2, "0"); //January is 0!
let yyyy = aux.getFullYear();
let today = yyyy + "-" + mm + "-" + dd;
let other = "2019-01-31";
}
The problem is that I use this variable directly in my HTML how I previously showed. The error I get is the following:
ERROR Error: ExpressionChangedAfterItHasBeenCheckedError: Expression
has changed after it was checked. Previous value: 'ngIf: undefined'.
Current value: 'ngIf: true'.
So the problem is that I am using a variable in the HTML file before getting the value. Or at least it is what I understand
To check this error I have created a Stackblitz representation. On it, I have created two examples:
Variables not on ngOnInit()
Variables in ngOnInit()
https://stackblitz.com/edit/angular-jjgsmq?file=src%2Fapp%2Fhello.component.ts

the most simple solution is just to
and are you sure that ngOnInit is the right LifeCycle hook for you?
I would try ngAfterContentInit() if the component is "heavy" to render other wise ngAfterViewInit() would have been my choice
<div *ngIf="IsTodayBigger()">
ngOnInit() {
this.getCurrentDate();
}
IsTodayBigger(): boolean {
today=this.getCurrentDate()
exampleEndDate= example.endDate;//use binding or ViewChild if needed
return today&&exampleEndDate&& today> example.endDate
}
//Get current date
getCurrentDate() {
let aux = new Date();
//2 characteres
let dd = String(aux.getDate()).padStart(2, "0");
let mm = String(aux.getMonth() + 1).padStart(2, "0"); //January is 0!
let yyyy = aux.getFullYear();
today = yyyy + "-" + mm + "-" + dd;
let other = "2019-01-31";
}

Related

Check date is correct + regex Angular4

I have a form in Angular4, with 2 dates: started, finished.
I want to check that the format date is dd/mm/yyyy.
I wrote:
<input pattern="((0)*[1-9]|[1-2][0-9]|(3)[0-1])(\/)(((0)*[1-9])|((1)[0-2]))(\/)\d{4}$" [(ngModel)]="filterDateStart" class="form-control" type="date" id="filterDateStart" name="filterDateStart" clrDate>
<input pattern="((0)*[1-9]|[1-2][0-9]|(3)[0-1])(\/)(((0)*[1-9])|((1)[0-2]))(\/)\d{4}$" [(ngModel)]="filterDateEnd" class="form-control" type="date" id="filterDateEnd" name="filterDateEnd" clrDate>
Then when I write invalid dates , my html doesn't say anything... I can send this form.
Then I need to check these dates.
1º Date start < date end
2º Ranges valid -> (30/20/2018) or (32/12/2018)
I see the library moment.js, but my boss says that I don't should be it. thanks, sorry for my english.
Don't use regexes, rely on the Date API :
const valid = '12/12/2018';
const invalid1 = '12/12';
const invalid2 = '12.12.2018';
const invalid3 = 'foo';
function parseDate(date) {
try {
// Make your business logic here. Examples : all must be defined and numbers, and separated with a /
const [d, m, y] = date.split('/');
if (!d || !m || !y) throw new Error();
if(isNaN(d) || isNaN(m) || isNaN(y)) throw new Error();
return new Date(y, m, d);
} catch(err) {
return 'Invalid date';
}
}
console.log(parseDate(valid));
console.log(parseDate(invalid1));
console.log(parseDate(invalid2));
console.log(parseDate(invalid3));
With that you can create a custom validator, that will be a lot more explicit than using a pattern.

Converting mysql date to js date works in chrome but not safari

I am using a pipe in angular2 to convert a mysql date to a js date format here is my code:
export class DateToIso {
transform(value) {
let date = new Date(value);
let str = (date.getMonth() + 1) + '.' + date.getDate() + '.' + date.getFullYear()
return str;
}
}
In HTML I use
{{ post[2] | dateToIso}}
to show the converted date. In Chrome I get the correct datetime but not in safari. It returns NaN.NaN.NaN.
I had a similar problem with the currency pipe and it was an internationalization issue. I wrote it up here http://blogs.msmvps.com/deborahk/angular-2-getting-started-problem-solver/
Install the international package: npm install intl#1.1.0 –save
Include the following in index.html:
(I'm using a touch device and the pasted code doesn't work. Please see the link)
I tried it #DeborahK but it didn`t work so I just took the Mysql date "String" and made substrings out of it and rearranged the substrings to a new string and returned it.
export class DateToIso {
transform(value, args) {
let month = value.substr(5,2);
let day = value.substr(8,2);
let timeThen = value.substr(11,5);
let newValue = day + "." + month + " um " + timeThen;
return newValue;
}
}
I believe this is not the best solution but it is working. Hope to get better solutions soon.

Will Javascript read returned string as script or treat it as a string?

I am wondering is it possible to run a function that outputs a line that javascript can read and recognize as a variable and not as a string? I have pulled JSON data and what I want to do is to take the object data and dynamically write out variables from it on the fly. I hope this is possible..
function createVar(data){
return "var_" + data.name + data.id + "=_" + data.desc;
//This will return the line :
var itemModel1 = "I no longer vote";
}
I have to say that I don't really recommend this, but it does work.
function createVar(data){
return "var " + data.name + data.id + "='" + data.desc + "'";
}
var exampleData = {name:"itemModel", id:"1", desc:"Today we went to the mall"}
eval(createVar(exampleData));
console.log(itemModel1); //outputs "Today we went to the mall" to the console
I will clarify by saying that if you actually need to generate variable names on the fly, this will do the trick. But I would more closely examine your code to see if there is another way to accomplish what you are trying to do. As always, you have to be very careful with eval, bad things can happen if user input gets passed as your data parameter.

Google Docs Script Issue with Split through Function

First time poster here for Google Script related services, hopefully I put it in the right place! I'm encountering an error and I can't seem to find the right terminology to look up a solution. Below is the function. Within it I have a variable, string1, that I apply the split to. If I hard-code the value of the string (in the line commented out in the string), then it works and I receive the correct output. If, on the other hand, I try to pass that string into the function from another function, I receive the following error:
"TypeError: Cannot find function split in object Wed Oct 30 2013 09:00:26 GMT-0400 (EDT),danno,ticket,netid,request,mac,Error - Invalid Mac / Mac Not Found."
Note: My call to the function looks like this - formatEmailRow(completeEmailArray[i])
function formatEmailRow(rowToFormat) {
var formattedString = "";
var array1 = [];
var string1 = "";
///////////////////////
string1 = rowToFormat;
//string1 ="10/30/2013 9:00:26,danno,ticket,netid,request,mac,Error - Invalid Mac / Mac Not Found ";
///////////////////////
array1 = string1.split(",| ,|, ");
if (array1 != ""){
for (var i = 0; i < array1.length; i++) {
formattedString = formattedString + " " +(array1[i]);
}}
return formattedString;
}
Please help!
Thanks ahead of time, any advice is appreciated!
-Danno
You're getting that error because .split() isn't a method contained in the type of object you've passed in. Since you're new to this, it's worth a pause to read up on Objects and Methods - this is a quick overview.
You want to receive a String, but it seems that you're not. The problem will be with the code that's calling formatEmailRow().
My guess is that you're passing an array - probably all the cells in a row - but here's how you can check.
Add this line as the first line in your function:
Logger.log("rowToFormat = " + JSON.stringify(rowToFormat));
... then run, with your error. Check the logs - you want to see that you are getting a simple string. If you're getting an array, then you know what you need to fix. (Maybe you want to get the array after all!)

splite string using mutilple characters

what I need is simple thing, I have string which cantains data - time retrived from mySQL in mySQL format HH:MM:SS YY-MM-DD what I need is to split this string in actionscript to array of numbers like this
HH
MM
SS
YY
MM
DD
so I can compare it with current time, any one know how to splite using multiple delimiters at first, then compare it with current time. this is my work until now
var param:Array = datetime.split(" :-");
var currentTime:Date = new Date();
var seconds:uint = currentTime.getSeconds();
var minutes:uint = currentTime.getMinutes();
var hours:uint = currentTime.getHours();
var days:uint = currentTime.getDay();
var monthes:uint = currentTime.getMonth();
var years:uint = currentTime.getFullYear();
if(int(param[3]) > years)
return years + " سنة ";
if(int(param[4]) > monthes)
return monthes + " شهر ";
if(int(param[5]) > days)
return days + " يوم ";
if(int(param[0]) > hours)
return hours + " ساعة ";
if(int(param[1]) > minutes)
return minutes + " دقيقة ";
if(int(param[2]) > seconds)
return seconds + " ثانية ";
return param[0] + " يوم ";
`
Split allows the delimiter to be a regexp, so you can say this or that. Something like this:
myStr.split(/:|-/)
Good luck!
You can use multiple characters, with separated by pipe |
myStr.split(/:|-|[|\(|\)]/)
make sure to use \ if you use ( ) and similar, so ( )
To solve your specific question, you might consider replacing the characters to be the same, and then split on that one. Use datetime.replace(/[ :-]/g, "|") and then split on "|". (I didn't check the correctness of the regexp). What Tyler says is more elegant: datetime.split(/[ -:]/). I stand for the rest though:
What MySQL outputs (via php?) is a standard date notation. You could try and use the Date.parse(dateString) to get a timestamp from it, and convert that into a date object by passing it as the sole constructor parameter:
recordedTime = new Date(Date.parse(datetime));
You could then compare the two date objects directly.
if (recordedTime.getFullYear() > currentTime.getFullYear()) { ... }
Hope it helps.