I have a list with start dates and end dates columns with the data type DateTime. I want to construct a query that fetches all events that have the start date or the end date within the query date range. The problem is that the query uses and. So I only get events with start and end dates within the date range query. I tried replacing the and with or but I only get Unexpected token in the console. I looked at the docs. But could not solve it. Any suggestions?
This is my code:
var DateRAngeFormat = 'YYYY-MM-DDT00';
var ThreeMonthsEarlier = moment().add(-3, 'months').format(DateRAngeFormat),
ThreeMonthsFromNow = moment().add(3, 'months').format(DateRAngeFormat);
var url = `${_spPageContextInfo.webAbsoluteUrl}/_api/web/lists/getbytitle('Program')/items?$select=Title%2CKontaktperson%2CBokning_x0020_till%2CBokning_x0020_fr_x00e5_n%2CMax_x0020_antal_x0020_platser%2CID&$filter=Bokning_x0020_fr_x00e5_n%20ge%20datetime'${ThreeMonthsEarlier}%3A00%3A00'%20and%20Bokning_x0020_till%20le%20datetime'${ThreeMonthsFromNow}%3A00%3A00'`;
EDIT
I made a query using CAML query (serverside code) and I get the result I want. so my guess is that it is possible using the REST _api, I just have to figure out how.
var q = new CamlQuery() { ViewXml = "<View><Query><Where><Or><Gt><FieldRef Name='Bokning_x0020_fr_x00e5_n' /><Value IncludeTimeValue='TRUE' Type='DateTime'>2017-10-03T00:28:05Z</Value></Gt><Lt><FieldRef Name='Bokning_x0020_till' /><Value IncludeTimeValue='TRUE' Type='DateTime'>2010-04-02T00:28:08Z</Value></Lt></Or></Where></Query></View>"};
Looks like some issue with formatting.
You need to use $filter=(Bokning_x0020_fr_x00e5_n ge datetime'2017-10-03T00:28:05Z') and (Bokning_x0020_till le datetime'2010-04-02T00:28:08Z')
So, your url would be:
var url = `${_spPageContextInfo.webAbsoluteUrl}/_api/web/lists/getbytitle('Program')/items?
$filter=(Bokning_x0020_fr_x00e5_n ge datetime'2017-10-03T00:28:05Z') and (Bokning_x0020_till le datetime'2010-04-02T00:28:08Z')
$select=Title,Bokning_x0020_fr_x00e5_n,Bokning_x0020_till,Kontaktperson,Max_x0020_antal_x0020_platser;
Related
Goal
Write a script that does the following:
get data from sheet
modify column to flip names from [Last, First] to [First Last]
modify 2 columns to abbreviate company names & statuses
write resulting data to another spreadsheet without changing the format
add timestamp for when data copied
Problem
I can get the data BUT it writes everything back as plain text. Thus instead of dates writing out as "yyyy-MM-dd", they write out as something like this: Mon Oct 19 2020 01:00:00 GMT-0400 (Eastern Daylight Time)
Expectation:
screenshot of dates as "yyyy-MM-dd"
Result:
screenshot of dates as whatever this garble is
I have googled extensively and can't seem to find a solution. I believe my problem is with using toString() in the Array.map. I'm not sure how to restrict the map method to only the columns that need modifying. Right now it affects the whole array.
(I used the code from Google Apps Script for Multiple Find and Replace in Google Sheets to write this part)
//-----FIND AND REPLACE FOR COMPANY & STATUS ABBREVIATIONS
function replaceInSheet(initArray, to_replace, replace_with){
//Loop over rows in array
for(var row in initArray ){
//Use Array.map to execute a replace call on each of the cells in the row.
var replaced_values = initArray[row].map(function(originalValue){
return originalValue.toString().replace(to_replace,replace_with);
});
//Replace the original row values with the replaced values
initArray[row] = replaced_values;
}
}
Question--> How do I get the output of my script to format dates in two of my columns, correctly?
Attempted Solutions that didn't work
I tried swapping the name flip code to happen after the abbreviation code so I could add a setNumberFormat('yyyy-MM-dd') within the name flip for loop. I couldn't figure out how to apply this to columns within my array. Something like initarray[x][5].setNumberFormat("yyyy-MM-dd") gave me an error saying "TypeError: initArrayx.setNumberFormat is not a function"
I tried adding code before (and then even after) .setValues() at the end to change the format. Some resources I referenced:
setNumberFormat('yyyy-MM-dd') from stackoverflow: Set cell format with google apps script
Utilities.formatDate(new Date(), "CST", "yyyy-MM-dd") from stackoverflow: Get today date in google appScript
website post by BLACKCJ: "Cell Number Formatting with Google Apps Script"
google's developer documentation
and all sorts of other articles, blogs, forums, etc.
I tried writing a completely separate function to change the format after my script runs. Nope. I can't get those 2 columns to format as dates
Code & Sample Spreadsheet
Here's the whole code I'm using, modified to work with a sample google sheet I created just for the purposes of this question.
Sample Google Sheet:
https://docs.google.com/spreadsheets/d/1Ys77hQHHajIo-Xaxyom0SVnyVMZ6bKOT8Smpadd2jv4/edit?usp=sharing
Script:
// ==================================================
// FUNCTION TO RUN
// ==================================================
function syncData(){
//Ger Source Data
var ss = SpreadsheetApp.getActiveSpreadsheet();
var thisSheet = ss.getSheetByName("source");
var thisData = thisSheet.getRange("A4:M11");
var initArray = thisData.getValues();
//Get Target Location
var toSheet = ss.getSheetByName("target");
var toRange = toSheet.getRange("A4:M11"); //Range starts at A4
//CHANGE [LAST, FIRST] TO [FIRST LAST]
for (var x = 0; x < initArray.length; x++){
var indexOfFirstComma = initArray[x][0].indexOf(", ");
if(indexOfFirstComma >= 0){
//If comma found, split and update values in the values array
var lastAndFirst = initArray[x][0];
//Update name value in array
initArray[x][0] = lastAndFirst.slice(indexOfFirstComma + 2).trim() + " " + lastAndFirst.slice(0, indexOfFirstComma).trim();
}
}
//ABBREVIATE COMPANY
replaceInSheet(initArray, 'Bluffington School','BLF HS');
replaceInSheet(initArray, 'Honker Burger','HBGR');
replaceInSheet(initArray, 'Funky Town','FT');
//ABBRIVIATE STATUS
replaceInSheet(initArray, 'Regular','Staff');
replaceInSheet(initArray, 'Contractual','Part');
replaceInSheet(initArray, 'Temporary','Temp');
//Clear Target Location
var toClear = toSheet.getRange("A4:M11")
toClear.clearContent();
//Write updated array to target location
toRange.setValues(initArray);
//Write timestamp of when code was last run
setTimeStamp(toSheet);
}
//-----FIND AND REPLACE FOR COMPANY & STATUS ABBREVIATIONS
function replaceInSheet(initArray, to_replace, replace_with){
//Loop over rows in array
for(var row in initArray ){
//Use Array.map to execute a replace call on each of the cells in the row.
var replaced_values = initArray[row].map(function(originalValue){
return originalValue.toString().replace(to_replace,replace_with);
});
//Replace the original row values with the replaced values
initArray[row] = replaced_values;
}
}
//-----ADD TIMESTAMP FOR WHEN THE SCRIPT LAST RAN
function setTimeStamp(toSheet) {
var timestamp = Utilities.formatDate(new Date(), "CST", "yyyy-MM-dd # h:mm a");
toSheet.getRange('F1').setValue(timestamp);
}
setNumberFormat('yyyy-MM-dd') is a good solution but it's a method of a Range of the sheet. Not an array.
To apply the format you need to get a range first. Something like this:
toSheet.getRange('G4:G').setNumberFormat('yyyy-MM-dd');
And there is one more thing ) Try to change this line:
var initArray = thisData.getValues();
to:
var initArray = thisData.getDisplayValues();
I am receiving JSON that includes a time pair in the format:
"_changed": "2020-01-26T00:32:16.282Z"
How do I create a corresponding structure property that parses this into something I can display nicely in a view? Right now I simply have:
property (_changed){
type (core.Text)...
But this string is unwieldy and not suitable for display to users. I tried time.DateTimeExpression but that seems to be NL-oriented. How do I manipulate this into something I can display to users in a result view?
The easiest (and possible only) way is to do it in Java Script. There is not any NL training in viv.time can handle that.
Bixby has JS library that could parse this format, just do the following. Read more about dates library here
var dates = require('dates')
var console = require('console')
module.exports.function = function getToday () {
var res = dates.ZonedDateTime.parseDateTime("2020-01-26T00:32:16.282Z")
console.log('res', res)
return 'works!'
}
And check the debugger would see the result.
The following may not be the best Javascript code, but would get the job done for some non-supported format.
var str = "2020-01-26T00:32:16.282Z";
var res = str.split("T")[0].split("-");
var year = parseInt(res[0]);
var month = parseInt(res[1]);
var date = parseInt(res[2]);
You can do the same with hour/minute/second then create and return viv.time object in JS.
Hoping this is a simple problem for you lot. I have no coding knowledge at all. But been using the below script in a Google Sheet to grab changing data from another sheet and log it daily, appending as it goes. Can't remember where I found the script - if I did I'd go back and ask its creator. It's been working fine; only thing is I have to manually copy paste my preferred date format every day. So I'd like the script to print the date in "dd/MM/yyyy" format (while retaining hours and minutes data inside the cell). I've been reading and searching online, and experimenting for ages but can't figure it out. This is the base code:
function recordHistory() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName("History");
var source = sheet.getRange("A2:C2");
var values = source.getValues();
values[0][0] = new Date();
sheet.appendRow(values[0]);
};
I've tried placing setnumberformat in various places and nearly always get an error. Perhaps my best attempt, inspired by other examples I've seen, was to add these new lines:
function recordHistory() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName("History");
var source = sheet.getRange("A2:C2");
var values = source.getValues();
values[0][0] = new Date();
sheet.appendRow(values[0]);
var cell = SpreadsheetApp.getActiveSheet().getRange(2, 1, 979);
cell.setNumberFormat("dd/MM/yyyy");
};
I hoped this would format the entire date row (Row A) after appending the new data. Probably a clunky solution even if it worked, but it didn't. It's my only attempt so far that doesn't return an error! So, yay? But it doesn't change the date format. So I give up. Any ideas?
To specify the format for a specific cell
var cell = sheet.getRange("A2");
cell.setNumberFormat("dd/MM/yyyy");
To specify the format for a range of cells
var cells = sheet.getRange("A2:C2");
cells.setNumberFormat("dd/MM/yyyy");
Please see the documentation for Range and formats.
Just in case you need the time as well, follow this code.
var cell = sheet.getRange("A2");
cell.setNumberFormat("dd/MM/yyyy h:mm:ss AM/PM");
Am using moment JS to get the current time. Based on that time I need execute search operation in my elastic search database.
My database entry is like this way :
"message_date": "2014-03-20T09:17:40.482Z"
Moment code to get current time is like this way :
var m = moment();
var testResult = m.toJSON();
// It outputs : 2014-03-20T09:17:40.482Z
My problem is I don't want to include that seconds filed in my database query. I want to search only up to minute field i.e 2014-03-20T09:17. I can split the moment date to get the expected format. But i know its not the way to do that. Please help me to get the expected time format in moment JS way. Thanks
Try:
var testResult = m.format('YYYY-MM-DD[T]HH:mm');
If you want to get the time in a particular timezone:
var m = moment().zone("+05:30");
var testResult = m.format('YYYY-MM-DD[T]HH:mm');
Okay, I've been working on this for about a month. I've tried numerous different ways of doing this, and I think I'm close. I'm not an expert, but here is what I'm trying to do. I've created a form that allows me to capture behavior data for my son. (He's autistic, which is why this is important.) I can get the data from the form into a results spreadsheet and I can transfer the data to a new report style pre formatted spreadsheet. What I can't do is filter the dates effectively. My script is below.
function onOpen() {
var rawdata=SpreadsheetApp.openById("0AtkuL_H_DshvdFU5U1dBLVI1NWhlWXdSNjBXOHdIaUE");
var sheet1=rawdata.getSheetByName("FormResponses");
var maxrows=sheet1.getMaxRows();
var lastcol = sheet.getLastColumn();
var vals=sheet1.getRange(1,1,maxrows,1).getValues();
var date = new Date();
var newDate = date.setDate(date.getDate()+1);
var Sdate=Utilities.formatDate(date,"GMT-0400","yyyy:MM:dd");
var newerDate=Utilities.formatDate(newDate,"GMT-0400","yyyy:MM:dd");
var filter=ArrayLib.filterByDate(vals,1,Sdate,newerDate);
var range1 = sheet1.getRange(1,1,filter,lastcol);
var values = range1.getValues();
var target = SpreadsheetApp.openById("0AtkuL_H_DshvdGxWNGJ0ZjA2VU5zV01iaVNacDZQYWc")
var sheet2 = target.getSheetByName("Sheet1");
var range2 = sheet2.getRange(4,1,i,7);
SpreadsheetApp.setActiveSpreadsheet(rawdata);
values
SpreadsheetApp.setActiveSpreadsheet(target);
range2.setValues(values);
}
//for (var i = 0; i < maxrows; i++) if (Date.parse(vals[i]).valueOf() >= todaydt.valueOf() );
The last line is a prior way I tried to filter the dates. That's the part I can't quite get to work. Part of my challenge is that I don't quite understand the "for" command yet. I'm doing the CodeAcademy java course, but since I work, have a family, and don't do this for a living its slow going. I've searched about a thousand websites and tried numerous ways to filter the dates, but I can't get any of them to work. Any help is appreciated.
I assume arraylib.filterbydate takes dates but you are passing strings. Try passing dates.
Or just filter by string if that lib allows it. Since you are formatting the date strings as yyyymmdd your string comparisons could work.