Utilities.formatDate - incorrect year in the formatted string [duplicate] - google-apps-script

This question already has answers here:
Y returns 2012 while y returns 2011 in SimpleDateFormat
(5 answers)
Closed 5 years ago.
In Google App Script consider the following date formatting code
function testDateFormatter(){
// Sun Dec 31 2017 20:02:06
var date = new Date(1514746926811)
var dateString = Utilities.formatDate(date, "CET", "YYYY-MM-dd");
Logger.log("The date is : " + date + ", after formatting it is " + dateString)
}
The result is:
//
// The date is : Sun Dec 31 2017 20:02:06 GMT+0100 (CET), after formatting it is 2018-12-31
//
note 2018 instead of 2017 !!!!
Why GAS added the whole year to the date?
With other sample dates it works fine i.e.:
var date = new Date(1511377747255)
var dateString = Utilities.formatDate(date, "CET", "YYYY-MM-dd");
Logger.log("The date is : " + date + ", after formatting it is " + dateString)
//
// Logger: The date is : Wed Nov 22 2017 20:09:07 GMT+0100 (CET), after formatting it is 2017-11-22
//

I don't see the problem:
function myFunction() {
var dt=new Date(1514746926811);
var dts=Utilities.formatDate(dt, Session.getScriptTimeZone(), "MM/dd/yyyy HH:mm:ss")//not YYYY
Logger.log('dt=%s dts=%s',dt,dts);
}
Logger Output is:
[17-12-22 15:17:07:058 MST] dt=Sun Dec 31 12:02:06 GMT-07:00 2017 dts=12/31/2017 12:02:06

Related

How do I enter multiple timestamps for multiple columns as they are modified?

I was able to modify if in any column within column 1 through 9 was modified the time stamp was entered on column 10 and last modified on column 11.
I know need to get granular and timestamp when each column is first modified, while maintaining the existing timestamp setting.
I believe this is as simple as an "if" statement but I can't seem to figure it out.
Here is what I have so far. This gives me the date and time any cell, between column 1 and 9 is first modified, on that row and returns date and time on column 10, then last modified date and time on column 11 if any changes are done.
Now i want to keep record of when column 1-9 are first modified as well, and enter them on the same sheet starting at column 12
function addTimestamp (e){
//variables
var startRow = 2;
var ws = "Daily Log"
var currentDate = 1
//get modified row and column
var row = e.range.getRow();
var col = e.range.getColumn();
if(([1,2,3,4,5,6,7,8,9].includes(col))&& row >= startRow
&&e.source.getActiveSheet().getName() ==ws){
var currentDate = new Date();
e.source.getActiveSheet().getRange(row, 11).setValue(currentDate);
if(e.source.getActiveSheet().getRange(row, 10).getValue()== ""){
e.source.getActiveSheet().getRange(row,10).setValue(currentDate);
} // END IF check if date created exists
} // END IF column, row, worksheet
}
Special thanks to #raygun who helped me in creating uniq driver IDs.
Explanation:
Your goal is:
Keep the datetime for which any cell in columns 1-9 is modified for the first time in column 10.
For every cell modified in columns 1-9 add a last modified stamp in columns 12-20 respectively. For example if column 1 is modified, update timestamp in column 12, if column 2 is modified update column 13 etc.
For performance reasons, it is always a good practice to store the code you are using often, in variables:
For example e.source.getActiveSheet() is used 4 times in your code and every time it is called, it consumes resources. You can instead store it in a variable and use that variable instead.
Solution:
function addTimestamp (e){
//variables
const startRow = 2;
const ws = "Daily Log"
//get modified row and column
const rng = e.range;
const as = rng.getSheet();
const row = rng.getRow();
const col = rng.getColumn();
if(col>=1 && col<=9&& row >= startRow && as.getName() ==ws){
const currentDate = new Date();
const rng_all = as.getRange(row, col+11);
const rng_ten = as.getRange(row, 10);
as.getRange(row,11).setValue(currentDate);
if(rng_all.getValue()== ""){
rng_all.setValue(currentDate)
}
if(rng_ten.getValue()== ""){
rng_ten.setValue(currentDate);
}
}
}
Side Note:
You don't need an installable trigger for this particular task. You can replace addTimestamp(e) with onEdit(e) (simple trigger) and it would also work. But it is up to you what you prefer, but it would be a good idea to read the differences (in the hyperlinks I provided).
Here's a function for logging all of your changes into a file:
function onMyEdit(e) {
e.source.toast('entry');
let sh = e.range.getSheet();
if (e.range.columnStart < 10) {
let f = DriveApp.getFileById('file id');
let c = f.getBlob().getDataAsString();
let ts = Utilities.formatDate(new Date(), Session.getScriptTimeZone(), "E MMM dd yyyy HH:mm:ss");
let o = c + ts + ',' + sh.getName() + ',' + e.range.rowStart + ',' + e.range.columnStart + ',' + e.oldValue + ',' + e.value + ',' + e.user.getEmail() + '\r\n';
f.setContent(o);
Logger.log(o);
}
}
Requires Installable Trigger
Data Table:
timestamp
sheetname
row
col
oldvalue
value
useremail
Sat Feb 13 2021 08:53:53 GMT-0700 (Mountain Standard Time)
Sheet1
5
4
30
55
Redacted
Sat Feb 13 2021 08:54:58 GMT-0700 (Mountain Standard Time)
Sheet1
9
4
32
55
Redacted
Sat Feb 13 2021 08:56:05 GMT-0700 (Mountain Standard Time)
Sheet1
14
7
62
new value
Redacted
Sat Feb 13 2021 08:56:45 GMT-0700 (Mountain Standard Time)
Sheet1
1
2
10
45
Redacted
Sat Feb 13 2021 08:56:52 GMT-0700 (Mountain Standard Time)
Sheet1
3
2
11
77
Redacted
Sat Feb 13 2021 09:10:16 GMT-0700 (Mountain Standard Time)
Sheet2
5
2
4
77
Redacted
Sat Feb 13 2021 09:16:08 GMT-0700 (Mountain Standard Time)
Sheet5
8
4
undefined
666
Redacted
Sat Feb 13 2021 09:18:04 GMT-0700 (Mountain Standard Time)
Sheet5
13
7
undefined
66
Redacted
Sat Feb 13 2021 09:19:44 GMT-0700 (Mountain Standard Time)
Sheet5
9
3
undefined
66
Redacted
Sat Feb 13 2021 09:20:29 GMT-0700 (Mountain Standard Time)
Sheet5
11
7
undefined
kk
Redacted
Sat Feb 13 2021 09:22:21 GMT-0700 (Mountain Standard Time)
Sheet1
1
1
undefined
undefined
Redacted
Here's a utility for loading a simple csv into a spreadsheet:
function loadCSVintoSpreadsheet() {
const ss = SpreadsheetApp.getActive();
const ui = SpreadsheetApp.getUi();
const resp1 = ui.prompt('Select Sheet Name', 'Enter destination sheet name', ui.ButtonSet.OK_CANCEL);
if (resp1.getSelectedButton() == ui.Button.OK && resp1.getResponseText().length > 0) {
const sh = ss.getSheetByName('Sheet1');
sh.clearContents();
const resp2 = ui.prompt('CSV FileId', 'Enter file id of csv', ui.ButtonSet.OK_CANCEL);
if (resp2.getSelectedButton() == ui.Button.OK && resp2.getResponseText().length > 0) {
const file = DriveApp.getFileById(resp2.getResponseText());
const csv = file.getBlob().getDataAsString();
let csvA = Utilities.parseCsv(csv)
sh.getRange(1, 1, csvA.length, csvA[0].length).setValues(csvA);
}
}
}

Returning Dates In A Formatted Format (Iteration)

I am trying to create tabs with each tab name being the date of the start of each week in the year. So, "Jan 01" then "Jan 08" then "Jan 14" etc.
Essentially, taking x date then adding +7 days and returning that value as a date 7 days from x date.
function CreateWeekTabs(){
var TotalsSheet = spreadsheet.getSheetByName("Totals");
var StartingWeek = new Date(TotalsSheet.getRange("B1").getValue()); //Typically always "Jan 01" shwon. Cell Formatting is MMM DD. Cell Value is 01/01/2019
var CurrentWeek = new Date();
var NextWeek = new Date();
spreadsheet.toast("Please wait...","Creating Tabs");
for (var WeekNum = 1;WeekNum <= 2;WeekNum++){
var DayIncrease = 7 - (7 * WeekNum); //Should produce 0,7,14,21,28.... So first iteration won't increase any value from Jan 01.
CurrentWeek.setDate(StartingWeek.getDate()+DayIncrease); //E.g. First Iteration = Jan 01 + 0 = Jan 01; Second Iteration = Jan 01 + 7 = Jan 08;
NextWeek.setDate(CurrentWeek.getDate()+7); //Should be +7 days from CurrentWeek Value.
var WeekSheetName = Utilities.formatDate(NextWeek,spreadsheet.getSpreadsheetTimeZone(),"MMM DD"); //Should return the date formatted.
Logger.log(WeekNum+" - "+WeekSheetName);
}
}
With Each Iteration, I intend to create WorkSheets with the First Date of each Week Starting from Value of CurrentWeek
Eg: Jan 01, Jan 08, Jan 15, Jan 22, Jan 29, Feb 05, etc...
UPDATE:
I since changed the code to:
function CreateWeekTabs(){
var TotalsSheet = spreadsheet.getSheetByName("Totals");
var CurrentWeek = new Date(TotalsSheet.getRange("B1").getValue()); //Typically always "Jan 01" shown. Cell Formatting is MMM dd. Cell Value is 01/01/2019
// var CurrentWeek = new Date();
var NextWeek = new Date();
spreadsheet.toast("Please wait...","Creating Tabs");
for (var WeekNum = 1;WeekNum <= 12;WeekNum++){
var DayIncrease = (7 * WeekNum) - 7; //Should produce 0,7,14,21,28.... So first iteration won't increase any value from Jan 01.
CurrentWeek.setDate(CurrentWeek.getDate()+DayIncrease); //E.g. First Iteration = Jan 01 + 0 = Jan 01; Second Iteration = Jan 01 + 7 = Jan 08;
NextWeek.setDate(CurrentWeek.getDate()+DayIncrease+7); //Should be +7 days from CurrentWeek Value.
var WeekSheetName = Utilities.formatDate(NextWeek,spreadsheet.getSpreadsheetTimeZone(),"MMM dd"); //Should return the date formatted.
Logger.log("Week Number: "+WeekNum+" - Current Week: "+Utilities.formatDate(CurrentWeek,spreadsheet.getSpreadsheetTimeZone(),"MMM dd")+" Next Week: "+WeekSheetName);
}
}
and the Log is producing the following as outputs. (so I can see what it's producing for Variables 'CurrentWeek' and 'NextWeek'
[19-06-14 14:40:00:463 EDT] Week Number: 1 - Current Week: Jan 01 Next Week: Jun 08
[19-06-14 14:40:00:464 EDT] Week Number: 2 - Current Week: Jan 08 Next Week: Jun 22
[19-06-14 14:40:00:464 EDT] Week Number: 3 - Current Week: Jan 22 Next Week: Jul 13
[19-06-14 14:40:00:465 EDT] Week Number: 4 - Current Week: Feb 12 Next Week: Aug 09
[19-06-14 14:40:00:466 EDT] Week Number: 5 - Current Week: Mar 12 Next Week: Sep 16
[19-06-14 14:40:00:467 EDT] Week Number: 6 - Current Week: Apr 16 Next Week: Oct 28
[19-06-14 14:40:00:468 EDT] Week Number: 7 - Current Week: May 28 Next Week: Dec 16
[19-06-14 14:40:00:468 EDT] Week Number: 8 - Current Week: Jul 16 Next Week: Feb 10
[19-06-14 14:40:00:469 EDT] Week Number: 9 - Current Week: Sep 10 Next Week: Apr 13
[19-06-14 14:40:00:470 EDT] Week Number: 10 - Current Week: Nov 12 Next Week: Jun 21
[19-06-14 14:40:00:471 EDT] Week Number: 11 - Current Week: Jan 21 Next Week: Sep 06
[19-06-14 14:40:00:471 EDT] Week Number: 12 - Current Week: Apr 07 Next Week: Nov 30
Why the blazes? Current Value is calculating correctly, but the value of Next Week is way off, it should be showing +7 days from Current Week.
Try these:
The first calculates the start of week tab name for this week. You can pick the start of week day Sun-Sat is 0-6. The second calculates the start of week tab name for next week.
function thisWeeksStartOfWeekTabname(sow){
var sow=sow || 1;//Sun-0, Sat=6
var ss=SpreadsheetApp.getActive();
var dt=new Date();
while(dt.getDay()>0) {
dt=new Date(dt.setDate(dt.getDate()-1));
}
dt=new Date(dt.setDate(dt.getDate()+sow));
Logger.log(Utilities.formatDate(dt, Session.getScriptTimeZone(), "MMM dd"));
return Utilities.formatDate(dt, Session.getScriptTimeZone(), "MMM dd");
}
function nextWeeksStartOfWeekTabname(sow){
var sow=sow || 1;//Sun-0, Sat=6
var ss=SpreadsheetApp.getActive();
var dt=new Date();
while(dt.getDay()>0) {
dt=new Date(dt.setDate(dt.getDate()+1));
}
dt=new Date(dt.setDate(dt.getDate()+sow));
Logger.log(Utilities.formatDate(dt, Session.getScriptTimeZone(), "MMM dd"));
return Utilities.formatDate(dt, Session.getScriptTimeZone(), "MMM dd");
}

To convert the json date which is coming from solr to actual date (yyyy/mm/dd)

Var idate =res.results[r].date
date is coming from solr
The above line output is in the format
Mon Apr 22 14:49:00 2019
I have tried code but I am getting today's date I want the date which is coming from solr below is the code
Var idate2=new Date(idate)//idate I am passing which is coming from solr.....
Var n=idate2.Tolocaledatestring();
Console.log(n);
Output I am getting is 5/5/2019 but I want 22/5/2019.
Thanks
you can use this code for convert your date:
var date = new Date('Mon Apr 22 14:49:00 2019');
var day = date.getDate();
var month = date.getMonth();
var year = date.getFullYear();
var result = day + '/' + month + '/' + year; // output is 22/3/2019

Google Apps Script: comparing dates

I'm having a weird issue comparing dates in my Google Apps Script.
For this, my sheet has a date in cell.getValue() so on the
e.range.setNote(cell.getValue() + " --- " + startDate);
line, the note shows two dates that appear identical, but they aren't because the following if statement is not satisfied. Am I missing something here with the comparisons? Thanks.
function onEdit(e) {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sss = ss.getSheetByName("Sheet1");
var row = e.range.getRow();
var startDate = sss.getRange(row, 3).getValue(); //Wed Aug 10 2016 00:00:00 GMT-0600 (GALT)
var cell = ss.getSheetByName("Sheet2").getRange(1, 1);
e.range.setNote(cell.getValue() + " --- " + startDate); //Wed Aug 10 2016 00:00:00 GMT-0600 (GALT) --- Wed Aug 10 2016 00:00:00 GMT-0600 (GALT)
if (cell.getValue() === startDate){
cell.setBackground('blue');
}
}
I think you need to compare as dates https://stackoverflow.com/a/493018/1393023
Replace
cell.getValue() === startDate
to
cell.getValue().getTime && startDate.getTime && cell.getValue().getTime() === startDate.getTime()

How to get start date and end date of current month in AS3

I have 2 DateFields named startDate and endDate I want to set startDate's Selected date to Current months start date and endDate's Selected date to Current months End date.
How can I achieve this?
Thanks in advance...
You mean this?
package
{
import flash.display.Sprite;
public class DateExample extends Sprite
{
public function DateExample()
{
super();
var now:Date = new Date();
trace("now: " + now.toString());
var startDate:Date = new Date(now.fullYear, now.month, 1);
trace("start: " + startDate.toString());
var endDate:Date = new Date(now.fullYear, ++now.month, 0);
trace("end: " + endDate.toString());
}
}
}
output:
now: Fri Oct 21 00:15:09 GMT-0500 2011
start: Sat Oct 1 00:00:00 GMT-0500 2011
end: Mon Oct 31 00:00:00 GMT-0500 2011