.getMonth and .getYear etc. won't extract correctly from dates in Google Sheets - date

I have dates stored in a column of a Google Sheet and I want to extract parts of the dates such as year and month. I tried to follow examples I have found but they do not work. Here is the code:
var analysisSS = SpreadsheetApp.getActiveSpreadsheet();
var analysisSheet = analysisSS.getSheetName();
var monthsListRange = analysisSS.getRangeByName(MonthDateRange);
var monthsList = monthsListRange.getValues();
var monthPointer = 1;
var monthCode = monthsList[monthPointer].getMonth();
Which produces the error message:
TypeError: Cannot find function getMonth in object Sun Jan 01 2017 00:00:00 GMT-0800 (PST).DetailsDismiss
This is the correct date stored in the first cell of the spreadsheet column.

Related

Problem with understanding date formats in googleScripts

I made a few functions with GoogleSheets using AppsScripts for simple task a few times in previous years. I always had problems when taking dates from cells/ranges and processing them, but somehow alwaays found a workaround, so that I did not have to deal with it. Well, this time I can not find a workaround, so I will try to explain my problems with the following code:
function getDates(){
var s = SpreadsheetApp.getActiveSpreadsheet();
var sht = s.getSheetByName('Dates');
var date = sht.getRange(2,1).getValues();
Logger.log(date[0][0]); //output is Tue Jun 08 18:00:00 GMT-04:00 2021
var datumFilter= Utilities.formatDate(date[0][0], "GMT+1", "dd/mm/yy");
Logger.log(datumFilter); //output is 08/00/21
var outrng = sht.getRange(25,1);
outrng.setValue(date);
}
The first targeted cell ('var date') has a value of "9.6.21" in the spreadsheet. The cell is formatted as a date and it opens a calendar when double-clicked. When I set the new cells values (with 'outrng.setValue(date);'), the result is OK, with the same date as in the original cell.
But I do not need to simply transfer the values, I want to implement them in some loops and I have no idea how to simply get the date in the same format or at least the same date in the script as it is in the cell. As you can see from the logger, the values there are different. A simple d/m/yy format would be sufficient.
My spreadsheet settings are set to my local time (Slovenia, GMT+1).
I am guessing that I am missing some basics here. I have spent many hours trying to understand it, so any help is highly appreciated!
Cooper already answered all your questions in the comment. I'd like to add on and show you an example on what it would like and add some modifications.
Code:
function getDates() {
var s = SpreadsheetApp.getActiveSpreadsheet();
var sht = s.getSheetByName('Dates');
// get last row of the sheet
var lastRow = sht.getLastRow();
// get your sheet's timezone
var timezone = SpreadsheetApp.getActive().getSpreadsheetTimeZone();
var output = [];
// getValues is mostly used for multiple cells returning a 2D array
// use getValue for single cells to return its actual value
// but since function name is getDates, I assume column A is all dates
// so we fetch the whole column (A2:A[lastRow]) except the header
var dates = sht.getRange("A2:A" + lastRow).getValues();
// for each date on that column, we format the date to d/M/yy
// m/mm = minute
// M/MM = month
dates.forEach(function ([date]){
Logger.log(date);
var datumFilter= Utilities.formatDate(new Date(date), timezone, "d/M/yy");
Logger.log(datumFilter);
// collect all dates in an array
output.push([datumFilter]);
});
// assign all the dates in the array onto range B2:B
sht.getRange(2, 2, output.length, 1).setValues(output);
}
Sample data:
Logs:
Output:
Note:
The output on sheets is not equal to logs due to the formatting of my sheet.

Chrome is changing milliseconds to date in console

I'm trying to give a span element a id from milliseconds.
var span_id = new Date();
$('#query').append('<span id="'+span_id+'"></span><br>');
When i inspect the span element in the console it shows like this:
<span id="Tue Feb 09 2021 11:53:54 GMT+0100 (centraleuropeisk normaltid)"></span>
How can i save the time in milliseconds.. so that the span id will be a long number.. like: 1239484738329303
I've tried:
var d = new Date();
var n = d.getMilliseconds();
But this will only give me the milliseconds right now.. separated from the minutes, hours and date.. so it will end up short like: 281
This is not Chrome-only behaviour. Casting a date object to a string (which, by using it as an ID attribute, is what you're doing), well implicitly render it to its full textual representation.
Instead, you need the static Date.now();
Date.now(); //1612868588100

Calculating days between two dates with Flutter

I want to develop a small Flutter app that calculates the number of days between two dates, using the following steps :
Ask the user to type the first date (Turkish notation; with whitespaces: "dd mm yyyy")
Ask the user to type the second date.
After that the program should calculates the number of days between the two dates and display it.
Given dateText and dateText2, this will give you the days between:
var dateArray = dateText.split(' '); // [d, m, y]
var date = new DateTime(int.parse(dateArray[2]), int.parse(dateArray[1]), int.parse(dateArray[0]));
var dateArray2 = dateText2.split(' ');
var date2 = new DateTime(int.parse(dateArray2[2]), int.parse(dateArray2[1]), int.parse(dateArray2[0]));
var daysBetween = date2.difference(date).inDays;
print(daysBetween); // 365

Having issues with pulling a date from the spreadsheet

I am working with Google Scripts and here is my problem.
I am attempting to compare today's date with a date entered into column C in the spreadsheet. The code I have seems like it should work but when I use the logger to see the date it gives me "Wed Dec 31 19:00:00 GMT-05:00 1969" instead of 2018-07-29 1:00 PM.
I know I need to use the Utilities.formatDate in order to compare them but I can't seem to understand why it is not pulling the date in column C.
Here is my code below:
function sendEmail() {
var sheet = SpreadsheetApp.getActiveSheet();
var startRow = 3; // First row of data to process
var numRows = sheet.getLastRow()-1; // Number of rows to process
// Fetch the range of cells A2:B3
var dataRange = sheet.getRange(startRow, 1, numRows, sheet.getLastColumn());
// Fetch values for each row in the Range.
var data = dataRange.getValues();
//Logger.log(data); // give you the data you are looking at comparing
for (var i in data) {
var row = data[i];
var date = new Date();
//Logger.log(date); // sets to todays date and time.
var sheetDate = new Date(row[3]);
Logger.log(sheetDate); // date in the row you are comparing
You're not looking at the value in column C. The method getValues() returns a two-dimensional array, and arrays are 0-indexed. This means that you should be using a 2 (not a 3), when defining sheetDate.
var sheetDate = new Date(row[2]);
As mentioned in the comments, you don't need to use Utilities.formatDate(), but that's a separate issue. I would also try logging the value before converting it to a date (e.g. Logger.log(row[2])).

DataJS Rendering Date as /Date(1363708765000)/

I am accessing the SharePoint 2010 List WCF data service via DataJS and getting back date fields as /Date(1363708765000)/ does anyone have any idea how I can process this to display a proper date?
Note: I am posing here as I suspect this is a DataJS question more than a peculiarity of the ListData.svc in SharePoint.
What you're receiving back is a Unix epoch, which represents the number of milliseconds that have elapsed since Jan. 01 1970. Fortunately, JavaScript also uses this as its epoch, meaning you can create a new Date object using elapsed milliseconds as your input parameter:
var myDate = new Date(1363708765000);
console.log("UTC:" + myDate.toUTCString());
// outputs UTC: Tue, 19 Mar 2013 15:59:25 GMT
Of course, you'll have to parse out the integer portion of the date value you're getting back before you can use it to initialize a date. A reusable function might look like this:
function parseJsonDate( sDate ) {
var b, e, i;
b = sDate.indexOf('(');
e = sDate.indexOf(')');
i = sDate.substring(b+1,e);
if (isNaN(i)) { return null };
return new Date(parseInt(i));
}