`Formatting Dates with Google Script`

I am looking to modify the date format from "mmm-dd-yyyy" (Nov-11-2019) using my existing code.

Here is the code snippet:

    var timeStamp = data[i][timeStampappr];
    var formatted = (timeStamp.getMonth()+1) + '/' + timeStamp.getDate() + '/' + timeStamp.getYear();

The current format is 11/11/2019 and I would like it to appear as Nov-11-2019.

Answer №1

In situations where the timestamp may be a string or a date, using the following method allows for consistent performance. If the timestamp is a string, it will create a date properly. If it's already a date object, it simply creates another date object with the same value. This approach can be useful when unsure of the type of data in the timestamp. Also, remember that capitalizing the M's in the format is necessary for the Month.

Utilities.formatDate(new Date(timestamp), Session.getScriptTimeZone(), "MM-dd-yyyy");

Simple Date Formatting Reference

JavaScript Date Constructor

Answer №2

Wonderful inquiry! In cases where a more specific function is not available, a simple solution is to create an array consisting of the string representation of each month. For instance:

var monthsAsStrings = ["Jan", "Feb", "Mar", ... ];
var formatted = monthsAsStrings[timeStamp.getMonth() + 0 ] + '-' + timeStamp.getDate() + '-' + timeStamp.getYear();
                     ^                                 ^      ^            

Keep in mind that array indices begin at 0, even though we typically refer to January as month 1. The + 0 may not be necessary, but it highlights the distinction between your provided code snippet and the desired outcome.

Furthermore, the '/' character has been substituted with '-' for formatting purposes.

Answer №3

To ensure proper date formatting, it is important to first check if a timestamp exists:

function checkTimestamp(data) {
  var timeStamp = data[i][timeStampappr];
  // Only format the date if a timestamp is present
  if(timestamp){
    var formattedDate = Utilities.formatDate(timestamp, "GMT", "MMM-dd-yyyy");
    Logger.log(formattedDate);
  } 
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Place a checkbox at the start of each table cell

Is there a way to add a checkbox before the text in the first cell of each row in an HTML table using jQuery? I attempted this method: $("table td:first-child").each(function() { $(this).prepend('<input type="checkbox" class="basic-kpi-row"/&g ...

What is the best way to switch a boolean state in React using TypeScript?

Hey there! I'm diving into the world of React and TypeScript. My goal is to toggle a boolean state (true/false) using a handler function. While I've come across solutions in ES6, I'm struggling to grasp how it can be implemented in TypeScri ...

JS seems to kick in only after a couple of page refreshes

I'm facing an issue with my 3 columns that should have equal heights. I've implemented some JavaScript to achieve this, which you can see in action through the DEMO link below. <script> $(document).foundation(); </script> <scri ...

Toggle Jquery feature will dynamically add the "required" attribute to the input field when the specified div is visible, and it will automatically remove the attribute when the div

I am new to using jQuery and I am facing an issue with my code. I want to make a checkbox act as a toggle with jQuery. When the checkbox is clicked and the toggle displays the div, I want to add the required attribute to the checkbox input. Similarly, when ...

Unit testing setTimeout in a process.on callback using Jest in NodeJS

I've been struggling with unit testing a timer using Jest within my process.on('SIGTERM') callback, but it doesn't seem to be triggered. I have implemented jest.useFakeTimers() and while it does mock the setTimeout call to some extent, ...

Narrow down an array of objects by matching a specific property and value to a separate array of objects

I am facing a challenge with two sets of arrays - one for the headers (columns) of a table and the other for the rows. const headers = [ { text: 'Dessert (100g serving)', align: 'left', sortable: false, value: 'n ...

Leverage the Power of Two AngularJS Factories

Can I efficiently use two Factories in AngularJS by calling one from the other? Here's the Scenario: I have a Factory that returns an Array. This Factory is responsible for checking if the data to populate this Array already exists in local SQL Stor ...

Exploring the complexities of object scope in Javascript

I'm having trouble accessing certain variables from a function. Here's the issue I'm facing: var PTP = function (properties) { this.errorsArray = [] } PTP.prototype.initHTMLItems = function () { $('input[data-widget-type="dat ...

Using React to dynamically assign a backgroundImage based on a JSON response

I am having an issue with retrieving data from my Wordpress API and displaying it in my react app. Specifically, I am struggling to set the post's featured image as a background-image for an element. Here is an example of the JSON response: { "id" ...

Multiple requests are being sent via AJAX

Despite numerous other posts addressing the same issue, I have not been able to find a solution for my problem. The AJAX request appears to be sent multiple times. var checkAllStatus = function () { $.ajax({ cache: false, type: "POST", ...

Consolidation of files for Client-Code-Generation with Swagger-Codegen: What is the best way to merge all files into

Just recently started using Swagger and NodeJS, I successfully integrated Swagger into my NodeExpress application and generated typescript-client-code with Swagger-Codegen (specifically Typescript-Angular). However, the issue I am facing is that the gener ...

What is the best way to retrieve the current value of a React useState hook within a setInterval function while using Highcharts

import Error from 'next/error' import React, { useState, useEffect } from 'react' import Highcharts from 'highcharts' import HighchartsReact from 'highcharts-react-official' function generateChart() { const [co ...

Angular directive for automatically selecting a <select> value when there is only one option available in ngOptions

How can I create a directive that automatically preselects an option if only one item is available in the ngOptions scope? Currently, my code looks like this: <select id="provider" name="provider" class="form-control" ng-model="foo.provider" ...

Rendering Highcharts React Pie Chart Multiple Times

Here is the code snippet: import React, { useEffect, useRef, useState } from "react"; import * as Highcharts from "highcharts"; import HighchartsReact from "highcharts-react-official"; export const PieChart = (props: any) =&g ...

Recurrence of solely the middle segment of the separator's background picture

I have a unique divider image with fading top and bottom parts. I'm wondering if it's possible to use a sprite and 3 divs to only repeat the middle section, considering that my height is variable. Do I need separate images for the top, middle, an ...

Can you explain the concept of a "cURL" and guide me on how to use it effectively?

I'm currently working on setting up a Lyrebird application, but I only have a basic understanding of javascript and php. Despite my efforts to implement a cURL request from , I've encountered issues trying to get it to work in both javascript and ...

Exploring the features of NextJS version 13 with the benefits

Starting from the 13th step, SSR is utilized by default and in order to opt for client side rendering you must specify it at the top like so: 'use client' Currently, my setup involves TypeScript and styled-component integration. Take a look at ...

An easy way to adjust the date format when linking a date in ng-model with md-datepicker

<md-input-container> <label>Scheduled Date</label> <md-datepicker ng-model="editVersionCtrl.selectedPlannedDate" ng-change="editVersionCtrl.checkPlannedDate()"> </md-datepicker> </md-input-container> ...

Here is a way to prevent a null input value from being accepted in a JavaScript function

Hey there, I have a function that looks like this: class Fun { pem_Files_Checker_And_Adder_Server_Id_Adder(id , serverType , hostname) { //do something }; }; } In order for this function to work properly, I need to give it some values. For exam ...

Vercel deployment issue: Hidden input values not being detected as expected

Whenever I attempt to update the data on Vercel, an error message is displayed: invalid input syntax for type uuid: "undefined" - unable to save Oddly enough, the data updates successfully when done locally. This is how I submit the form: <form onSu ...