Get today date in Google Apps Script - javascript

How do I get the Today date on google appscript?
I need to write a code to input today´s date in a cell.
function changeDate(){
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(GA_CONFIG);
var date = //Today´s date!?!?!!?
var endDate = date;
sheet.getRange(5, 2).setValue(endDate);
}

Utilities.formatDate(new Date(), "GMT+1", "dd/MM/yyyy")
You can change the format by doing swapping the values.
dd = day(31)
MM = Month(12) - Case sensitive
yyyy = Year(2017)
function changeDate() {
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(GA_CONFIG);
// You could use now Date(); on its own but it will not look nice.
var date = Utilities.formatDate(new Date(), "GMT+1", "dd/MM/yyyy")
var endDate = date
}

The Date object is used to work with dates and times.
Date objects are created with new Date()
var now = new Date();
now - Current date and time object.
function changeDate() {
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(GA_CONFIG);
var date = new Date();
sheet.getRange(5, 2).setValue(date);
}

Google Apps Script is JavaScript, the date object is initiated with new Date() and all JavaScript methods apply, see doc here

The following can be used to get the date:
function date_date() {
var date = new Date();
var year = date.getYear();
var month = date.getMonth() + 1; if(month.toString().length==1){var month =
'0'+month;}
var day = date.getDate(); if(day.toString().length==1){var day = '0'+day;}
var hour = date.getHours(); if(hour.toString().length==1){var hour = '0'+hour;}
var minu = date.getMinutes(); if(minu.toString().length==1){var minu = '0'+minu;}
var seco = date.getSeconds(); if(seco.toString().length==1){var seco = '0'+seco;}
var date = year+'·'+month+'·'+day+'·'+hour+'·'+minu+'·'+seco;
Logger.log(date);
}

Easiest way, you can use javascript date object which is new Date().
function changeDate(){
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(GA_CONFIG);
var date = new Date();
sheet.getRange(5, 2).setValue(date);
}
But then you will get the whole time object. You just need to change the format in spreadsheet to time or date, whatever you like.

function myFunction() {
var sheetname = "DateEntry";//Sheet where you want to put the date
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(sheetname);
// You could use now Date(); on its own but it will not look nice.
var date = Utilities.formatDate(new Date(), "GMT+5:30", "yyyy-MM-dd");
//var endDate = date;
sheet.getRange(sheet.getLastRow() + 1,1).setValue(date); //Gets the last row which had value, and goes to the next empty row to put new values.
}

Related

JavaScript for date range is only working with in a limit

I am trying to find the dates between two dates. I am attaching the script I have been using. It is working only if the start date and end date falls in between 4 months. If it is more than that it is failing.
Input I am passing ("01/01/2019","06/01/2019",1). What logic can I change here to get all the dates for larger date range.
WScript.StdOut.WriteLine(fnGetDateListInDateRange());
function fnGetDateListInDateRange() {
var addDays = WScript.Arguments.Item(2);
var startDate = WScript.Arguments.Item(0);
var endDate = WScript.Arguments.Item(1);
startDate = new Date(startDate);
endDate = new Date(endDate);
//
if (startDate > endDate)
{
return "-1";
}
//
var outputDate = new Array();
var tmpDate = new Date(startDate);
do {
outputDate.push(new Date(tmpDate));
tmpDate.setDate(tmpDate.getDate() + parseInt(addDays));
} while (tmpDate <= endDate);
//
return outputDate;
}

Wrong month is displayed from new Date()

I have been testing moment js on jsfiddle and i am trying varius things such as displaying month,day and formatting dates but the month comes out wrong
This is the code link
https://jsfiddle.net/codebreaker87/z9d5Lusv/37/
and this is the code itself
var day = moment().format('dddd');
var month = moment().format('MMMM');
var date = moment().format('d');
var year = new Date().getFullYear();
var nmonth = new Date().getMonth();
var gt = new Date().getTime();
var dotdate = date+'.'+nmonth+'.'+year;
var newdate = new Date();
alert(nmonth);
alert(newdate);
alert(dotdate);
alert(gt);
var fd = moment().format('dddd, MMMM d');
var fdf = moment().format('DD-MM-YYYY');
var nd = moment(dotdate, "DD-MM-YYYY").add(5, 'days');
var frt = nd.format('dddd, MMMM d');
alert('Weekday,Month Day:: '+fd);
alert('Five Days Later:: '+nd);
alert('Five Days Later into Weekday,Month Day Format:: '+frt);
The code displays the current month as 10 instead of 11.
Why is it displaying the month this way?.

Convert UTC to local time Javascript

I'm trying to convert UTC time to local time, but the below code is not working. What's wrong in it?
var parsedStartDateTime =
new Date(moment.unix(parseInt(data['StartDateTime'].substr(6)) / 1000));
var startDateTimeMoment =
moment.tz(parsedStartDateTime, tzName);
var formatted_date =
startDateTimeMoment.format("MMM DD YYYY h:mm:ss A");
To format your date try this:
var d = new Date();
var formatD = d.toLocaleFormat("%d.%m.%Y %H:%M (%a)");
Reference: Javascript to convert UTC to local time
Try appending UTC to the string before converting it to a date then use toString() method of date.
Example:
var myDate = new Date('7/1/2014 5:22:55 PM UTC');
date.toString(); //this should give you local date and time
This code was taken from here
Here is my solution:
function convertUTCDateToLocalDate(date) {
var newDate = new Date(date.getTime()+date.getTimezoneOffset()*60*1000);
var offset = date.getTimezoneOffset() / 60;
var hours = date.getHours();
newDate.setHours(hours - offset);
return newDate;
}
var date = convertUTCDateToLocalDate(new Date(date_string_you_received));
date.toLocaleString().replace(/GMT.*/g,"");

Javascript OO Function

I need something obvious pointing out to me in regard to JS functions.
The following code works, but I want to call upon it anywhere:
var pattern = /(\d{2})\-(\d{2})\-(\d{4})/;
var date = entry.date.split(' ');
var date = date[0];
var date = new Date(date.replace(pattern,'$3-$2-$1'));
var year = date.getYear();
var month = date.getMonth();
var day = date.getDay();
What would be the best practice to place this in a global function so I can just do adjustDate(string). Double points (Sadly, not in my power) to explain how I would then also have access to all the objects such as year, month, day.
Thanks in advance!
Can't you just declare the function?
function adjustDate(entry) {
var date = entry.date.split(' ');
date = date[0];
date = new Date(date.replace(/(\d{2})\-(\d{2})\-(\d{4})/, '$3-$2-$1'));
return {
year: date.getYear(),
month: date.getMonth(),
day: date.getDay()
};
}
I would just return a date without abstracting its existing methods
function AdjustedDate(dateString)
{
return new Date(dateString.split(' ')[0].replace(/(\d{2})\-(\d{2})\-(\d{4})/, '$3-$2-$1'));
}
var ad = AdjustedDate(entry.date);
alert(ad);
alert(ad.getDay());
Pass the entry into the function and then pass an object containing the information you want out. Then just access it like you would an ordinary JS object.
function adjustDate(entry) {
var pattern = /(\d{2})\-(\d{2})\-(\d{4})/;
var date = entry.date.split(' ');
var date = date[0];
var date = new Date(date.replace(pattern,'$3-$2-$1'));
var year = date.getYear();
var month = date.getMonth();
var day = date.getDay();
return { day: day, month: month, year: year }
}
var dateObject = adjustDate(/*entry*/)
dateObject.day // day
dateObject.month // month

Getting day of the week from timestamp using JavaScript

How do I get the day of the week from a timestamp in JavaScript?
I'd like to get this from a timestamp I specify, not the current date.
Thanks
var timestamp = 1400000000;
var a = new Date(timestamp*1000);
var days = ['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday'];
var dayOfWeek = days[a.getDay()]
Now the "day of the week" is in the dayOfWeek variable.
var timestamp = 654524560; // UNIX timestamp in seconds
var xx = new Date();
xx.setTime(timestamp*1000); // javascript timestamps are in milliseconds
document.write(xx.toUTCString());
document.write(xx.getDay()); // the Day
2020 Update
If this browser support is acceptable for you you can use this one liner:
new Date(<TIMESTAMP>).toLocaleDateString('en-US', { weekday: 'long' }); // e.g. Tuesday
Similar to klidifia's answer, but for some reason the day of the week was off. I had to update the 'days' array to start on Monday.
var timestamp = 1400000000;
var a = new Date(timestamp*1000);
var days = ['Monday','Tuesday','Wednesday','Thursday','Friday','Saturday', 'Sunday'];
var dayOfWeek = days[a.getDay()]
Try out the following:
var currentTime = new Date();
var day = currentTime.getDate();

Categories