Values Identical but not equal - javascript

Image of my array valuesI have a function to "Wed 12/8" and "Wed 12/8". However, when I use them in this function they are not equal for some reason yet they are identical. The function does not append and acts as if they are completely different.
function filterDate() {
for (var i = 0; i < dateList.length; i++) {
if(dateList[i] == today) {
appendItem(filteredDate, dateList[i]);
appendItem(filteredID, stateID[i]);
appendItem(filteredCase, totalCases[i]);
appendItem(filteredState, usState[i]);
}
}
}
Here the get date code.
//Date
var now = new Date();
//Gets the current days date
var days = ['Sun','Mon','Tue','Wed','Thu','Fri','Sat'];
var months = ['1','2','3','4','5','6','7','8','9','10','11','12'];
var weekday = days[now.getDay() - 1];
var day = now.getDate() - 1;
var month = months[now.getMonth()];
var today = weekday + " " + month + "/" + day;
//Console logs todays date
console.log(today);
The values are the exact same but the computer thinks they are not. When I manually change today to "Wed 12/8" it works but the variable seems to mess it up though I may be wrong. What's happening and how do I fix this as it is crucial to my program?

The problem should be the way you populate the dateList array. Are you sure it gets filled with strings too, and not for example date objects? The code you provided does not show anything related to that array.
Edit:
Based on the image you provided later, I think the issue will be that your strings in the array contain quotation marks.
Remove them from the strings. (For example by slicing the first and last characters from it in the filterDate function)
function filterDate() {
for (var i = 0; i < dateList.length; i++) {
if(dateList[i].slice(1,-1) == today) {
appendItem(filteredDate, dateList[i]);
appendItem(filteredID, stateID[i]);
appendItem(filteredCase, totalCases[i]);
appendItem(filteredState, usState[i]);
}
}
}

Related

Compare hours with google-script

I am new in the world of programming: D and I have a doubt about the comparison of hours.
I have a sheet with the following information
Name | Time out | Time in |
nam_1 10:00:00
nam_2 09:00:00
Time out hours have been entered using this code:
var start = Utilities.formatDate (new Date (), "Europe / Berlin", "HH: mm: ss");
sheet.appendRow([name, start]);
What I would like to try is:
var time_in = "13:00:00";
if time out> 13:00:00:
sheet.getRange(j+1, 2).setValue(time_in);
The problem is that I do not know exactly how to do it. What I have tried for now is:
function getTimeFromDateStartUserInput(date) {
return Utilities.formatDate(date, "Europe/Berlin", "HH:mm:ss");
}
function insertTimeIn(){
var file = DriveApp.getFilesByName("MySheet");
var doc = SpreadsheetApp.open(file.next());
var sheet = doc.getSheetByName("Sheet1");
if(sheet!=null){
var dataRange = sheet.getDataRange();
var values = dataRange.getValues();
var time_in = new Date ('30/12/1899 17:00:00');
time_in.setHours(13,0,0,0);
var inFormated = getTimeFromDate(time_in);
for(var i = 0; i<values.length; i++){
if(values[i][1]>=inFormated && values[i][2]=""){
sheet.getRange(j+1, 2).setValue(time_in);
}else{
sheet.getRange(j+1, 2).setValue("Nop");
}
}
}
However, I have not achieved anything with that code.
I think the problem may be that any entry in the "Time out" column has this design: Sat Dec 30 14:51:22 GMT + 01: 00 1899.
Therefore I think it does not work since I am comparing an hour with a complete Date object.
The logical thing I think it would be to call the function getTimeFromDateStartUserInput for all the input of values[i][1] but I do not know how to do it.
Could someone help me with this problem?
This is my guess at what you are trying to do. It doesn't work because it still contains errors. I commented on a few of them but I can't fix them because it's still not clear what you are trying to do..
function insertTimeIn(){
var files = DriveApp.getFilesByName('SpreadsheetName');
var n=0;
while(files.hasNext()){
var file=files.next();
}
if(++n>1){
throw("Error: There is more than one file with that name in function insertTimeIn");
return;
}
if(file.getMimeType()==MimeType.GOOGLE_SHEETS){
var doc=SpreadsheetApp.openById(file.getId());
var sheet=doc.getSheetByName("Sheet1");
if(sheet!=null){
var dataRange=sheet.getDataRange();
var values=dataRange.getValues();
var time_in=new Date(1899,11,30,13,0,0);
var inFormated=Utilities.formatDate(time_in, Session.getScriptTimeZone(), "HH:mm:ss");//it returns a string not a date
for(var i=0;i<values.length;i++){
if(values[i][1]>=inFormated && values[i][2]=""){//informated is a string not a date so greater than doesn't really make much sense here.
sheet.getRange(j+1, 2).setValue(time_in);//j is undefined
}else{
sheet.getRange(j+1, 2).setValue("Nop");//again j is undefined
}
}
}
}
}
A simple answer might be to auto convert the initial timestamp to the current date. I'm not entirely sure what the use of your sheet is going to be but I use a sheet for time entry and use the function onEdit() to verify that the user put the dateTime in correctly.
function onEdit(){
if(cell.getValue() instanceof Date === true){
if(cell.getValue().getFullYear()<2018 ){
formatDate();
}
}
}
function formatDate() {
var timeValue, cell,hour,minute,time,row,dateObj,month,day,year,newDate
cell = SpreadsheetApp.getActive().getActiveCell()
timeValue = cell.getValue()
hour = timeValue.getHours()
minute = timeValue.getMinutes() < 10? '0'+timeValue.getMinutes(): timeValue.getMinutes();
time = hour+":"+minute
row = cell.getRow()
dateObj = new Date();
month = dateObj.getUTCMonth() + 1; //months from 1-12
day = dateObj.getUTCDate();
year = dateObj.getUTCFullYear();
newDate = month + "/" + day + " "+ time; // formatted dateTimestamp to replace timestamp with
cell.setValue(newDate)
}
Let me know if that works for you. In my application, the onEdit function checks the active cell and continues if the entered value is a dateTime. If it is, it check what year the date is (time values alone are automatically 12/30/1899 and therefore throw wild numbers out when getting durations between a dateTimestamp and a timestamp with no date.

How to exclude weekends in date object in Javascript

I'm facing issue with excluding weekend dates in JavaScript.For my business requirement I want to exclude 3 days from date object Friday, Saturday and Sunday in every week.What I need here is the values of Friday should display as Monday, Saturday as Tuesday and Sunday as Wednesday. I'm able to do this.
The issue that I'm facing here is when we run the above example the a[0] value should be 21-SEP-2017 but I'm getting 20-SEP-2017 and remaining array values should not change. So please do help me out in resolving this issue
var a = ["21-SEP-2017", "22-SEP-2017", "23-SEP-2017", "24-SEP-2017", "25-SEP-2017"];
for (i = 0; i < a.length; i++) {
var startDate = a[i];
startDate = new Date(startDate.replace(/-/g, "/"));
var endDate = "",
noOfDaysToAdd = 1;
var count = 0;
endDate = new Date(startDate.setDate(startDate.getDate()));
if (startDate.getDay() != 0 && startDate.getDay() != 5 && startDate.getDay() != 6) {
endDate = new Date(startDate.setDate(startDate.getDate() + i - 1));
} else {
startDate.setDate(startDate.getDate() + 3)
endDate = new Date(startDate.setDate(startDate.getDate()));
}
console.log(endDate); //You can format this date as per your requirement
}
Your code seems not finished: the variables noOfDaysToAdd and count are never used, and if they were, they would be reset in every iteration of the loop, which cannot be the purpose.
That your output shows 20 September is because you did not output a stringified version of the date, but the date object itself, and then console.log will display the date as a UTC date (notice the time part matches the timezone difference). Instead use .toString() or another way to turn the date to a localised string.
Here is how you could do it:
function toDate(s) {
return new Date(s.replace(/-/g, '/'));
}
function toStr(dt) {
var months = ["JAN","FEB","MAR","APR","MAY","JUN",
"JUL","AUG","SEP","OCT","NOV","DEC"];
return [('0'+dt.getDate()).substr(-2), months[dt.getMonth()], dt.getFullYear()]
.join('-');
}
var a = ["21-SEP-2017", "22-SEP-2017", "23-SEP-2017", "24-SEP-2017", "25-SEP-2017"],
add = 0;
var result = a.map(toDate).map(dt => {
dt.setDate(dt.getDate()+add);
var move = [0, 6, 5].indexOf(dt.getDay()) + 1;
if (move) {
add += move;
dt.setDate(dt.getDate()+move);
}
return dt;
}).map(toStr);
console.log(result);

Store every year directly from the date of entry of a user

Hi I need to store every year directly from the date of entry of a user to the business the problem is that every time I add a year is inserted between the day and month.
var yearOnCompany = moment(user.fecha_ingreso_empresa, "YYYYMMDD").fromNow();
var dateStart = moment(user.fecha_ingreso_empresa).format("DD-MM-YYYY");
console.log(dateStart);
//03-12-2009
var f = parseInt(yearOnCompany);
var yearsOfWork = [];
for(var i = 1; i <= f; i++)
{
dateStart = moment(dateStart, "DD-MM-YYYY").add(1, 'years').calendar();
yearsOfWork.push(dateStart);
}
console.log(yearsOfWork);
Result of this:
0:"12/03/2010"
1:"03/12/2011"
2:"12/03/2012"
3:"03/12/2013"
4:"12/03/2014"
5:"03/12/2015"
6:"12/03/2016"
7:"03/12/2017"
This is a subtle error! According to the moment docs https://momentjs.com/docs/#/displaying/ .calendar() uses a default date format, possibly using the locale of the environment, if none is provided, so here it looks like it's defaulting to MM/DD/YYYY, rather than the desired DD/MM/YYYY. So on the first iteration dateStart is converted to 12/03/2010 with the month and day swapped. Then on the next iteration it's converted back to DD-MM-YYYY, again with the day and month swapped, then when passed to .calendar() again the day and month swap again giving the correct format again.
A potential bug is that you're changing dateStart from a string to a moment object, so I'd rewrite the code like this:
var dateStart = moment(user.fecha_ingreso_empresa).format("DD-MM-YYYY");
var f = parseInt(yearOnCompany);
var yearsOfWork = [];
for(var i = 1; i <= f; i++)
{
dateStart.add(1, 'years');
yearsOfWork.push(dateStart.format("DD-MM-YYYY"));
}
console.log(yearsOfWork);
I think you have the problem with the format, correct me if I am wrong.
Please try this.
for(var i = 1; i <= f; i++)
{
dateStart = moment(dateStart , "DD-MM-YYYY").add(1, 'years');
yearsOfWork.push(dateStart.format('DD-MM-YYYY'));
}

Create javascript object containing # of days in a given month

I have the following code, which returns the number of days in a month:
daysInMonth(month:number, year:number) {
return new Date(year, month, 0).getDate();
}
Let's say this gives me 31. Now, in my html, I want to create a dropdown element with all the days in the month, listed out in order. So, my dropdown would consist of:
1,2,3,4,5,6,7,8,9,10,11..... All the way to 31.
I need to build this object dynamically since the days in the month will change based on the month.
What's the most efficient way to do that?
I would use jQuery.
So somewhere along the line you'd do something:
var dropDown = $('<select/>').appendTo('body');
for (var i = 1; i <= daysOfMonth; i++) {
dropDown.append('<option value=' + i + '>' + i + '</option>');
}
You would clearly need to get the value of daysOfMonth from somewhere previously.
You can use the following to achieve the dropdown:
(function() {
var totalDays = daysInMonth(2, 2014),
selectEl = document.createElement('select');
for (var i = 1; i <= totalDays; i++) {
var option = document.createElement('option');
option.appendChild(document.createTextNode(i));
option.setAttribute('value', i);
selectEl.appendChild(option);
}
document.body.appendChild(selectEl);
}());
DEMO

Cant assign value from getElementById to date?

I've got this:
var lDate = document.getElementById('txtLeaveDate');
var rDate = document.getElementById('txtReturnedDate');
Err...javascript so how do I assign the value of txtLeaveDate to a date variable
I tried:
var myDate = new Date(lDate.value);
But this assigns some long value....
I can do it if I try:
var today = new Date();
var day2 = new Date();
day2.setDate(today.getDate() + 30);
But the issue is I need to get the date from txtLeaveDate not by a date variable
edit complete code
var theLDate = new Date(lDate.value);
var theRDate = new Date(rDate.value);
//check if return date is a sunday, if it is no need
//to do anything,
//else make it a sunday
while (theRDate.getDay() != 0)
theRDate.setDate(theRDate.getDate() + 1);
//at this point RDate is a sunday...
while(theLDate.valueOf() <= theRDate.valueOf())
{
if(theLDate.getDay() == 0)
{ //sunday
var li = document.createElement('li');
li.setAttribute('id', ['liID' + count]);
var month = theLDate.getMonth();
var day = theLDate.getDate();
var year = theLDate.getFullYear();
var theDay = month + '/' + day + '/' + year + ' (Sunday)';
li.innerHTML = theDay;
ul.appendChild(li);
}
theLDate.setDate(theLDate.getDate() + 1);
count++;
}
But when I pick 2 dates in my calendar like so:
if I try that and say alert(theLDate.valueOf()); it returns
1309924800000
That's because that is the value of a Date object, measured in milliseconds since 1/1/1970 00:00:00, in this case corresponding to Wed Jul 6 04:00:00 2011 UTC.
Try using .toString() instead and you'll see the corresponding date in a human readable format.
The problem with your dates appearing to be in June is because the getMonth() function for odd reasons returns the month zero based, i.e. January == 0.
You need to use .innerHTML, otherwise you are not returning the text in the element.
var lDate = document.getElementById('txtLeaveDate').innerHTML;
var myDate = new Date(lDate);
document.write(myDate);
http://jsfiddle.net/jasongennaro/ua85k/
Months returned by the someDate.getMonth method are zero-indexed (from 0 to 11). So if using them to create a string add 1!
var month = theLDate.getMonth() + 1;

Categories