Convert Firebase Cloud Functions timestamp to 'MM,DD,YYYY' format

Utilizing firebase functions, I am trying to retrieve a date that is 30 days from the current date in MM-DD-YYYY format. However, when attempting to import datepipe, I encountered an error stating: Detailed stack trace: Error: Cannot find module '@angular/common'.

index.ts:

import * as functions from "firebase-functions";
import * as admin from "firebase-admin";

admin.initializeApp();

exports.scheduledFunction =
 functions.pubsub.schedule("every 5 minutes").onRun((context) => {
   const currentDate = new Date();
   const targetDate = new Date().setDate(currentDate.getDate() + 30);
   console.log("Target Date" + targetDate);
   admin.database().ref("reservations/").update({zafer: "zafer5353"});
   return null;
 });

Console.log(targetDate) output is :1648669741663 How can I convert it to MM-DD-YYYY

package.json in functions:

{
  "name": "functions",
  "scripts": {
    "lint": "eslint --ext .js,.ts .",
    "build": "tsc",
    "serve": "npm run build && firebase emulators:start --only functions",
    "shell": "npm run build && firebase functions:shell",
    "start": "npm run shell",
    "deploy": "firebase deploy --only functions",
    "logs": "firebase functions:log"
  },
  "engines": {
    "node": "16"
  },
  "main": "lib/index.js",
  "dependencies": {
    "@angular/common": "^13.2.4",
    "@angular/fire": "^7.2.1",
    "firebase": "^9.6.7",
    "firebase-admin": "^9.8.0",
    "firebase-functions": "^3.14.1"
  },
  "devDependencies": {
    "@typescript-eslint/eslint-plugin": "^3.9.1",
    "@typescript-eslint/parser": "^3.8.0",
    "eslint": "^7.6.0",
    "eslint-config-google": "^0.14.0",
    "eslint-plugin-import": "^2.22.0",
    "firebase-functions-test": "^0.2.0",
    "typescript": "^3.8.0"
  },
  "private": true
}

Answer №1

To achieve your desired outcome, consider utilizing the toLocaleDateString() method.

Below are various options for formatting dates:

// The examples below assume the local time zone of the specified locale;
// For instance, America/Los_Angeles for the US

// In US English, the format is month-day-year
console.log(date.toLocaleDateString('en-US'));
// → "12/20/2012";

// British English follows a day-month-year format
console.log(date.toLocaleDateString('en-GB'));
// → "20/12/2012";

// Korean utilizes a year-month-day order
console.log(date.toLocaleDateString('ko-KR'));
// → "2012. 12. 20.";

// Persian requires special handling due to Solar Hijri date system
console.log(date.toLocaleDateString('fa-IR'));
// → "۱۳۹۱/۹/۳۰";

// Arabic speaking countries use real Arabic digits
console.log(date.toLocaleDateString('ar-EG'));
// → "٢٠‏/١٢‏/٢٠١٢";

// Japanese applications may opt for the Japanese calendar format
console.log(date.toLocaleDateString('ja-JP-u-ca-japanese'));
// → "24/12/20";

// When selecting an unsupported language like Balinese, include a fallback language like Indonesian
console.log(date.toLocaleDateString(['ban', 'id']));
// → "20/12/2012";

For a complete code reference, see below:

import * as functions from "firebase-functions";
import * as admin from "firebase-admin";

admin.initializeApp();

exports.scheduledFunction =
functions.pubsub.schedule("every 5 minutes").onRun((context) => {
   const a = new Date();
   const targetDate = new Date().setDate(a.getDate() + 30);
   const targetDateFormat = new Date(targetDate).toLocaleDateString("en-US", {
     year: "numeric",
     month: "2-digit",
     day: "2-digit"
   });
   console.log("Target Date: " + targetDateFormat);

   admin.database().ref("reservations/").update({zafer: "zafer5353"});
   return null;
 });

You can also customize the year, month, and date formats. Refer to this link for more details.

Another approach is using date objects. By accessing getters listed here, you can extract specific values and construct the desired string:

const curr_date = ("0" + new Date(targetDate).getDate()).slice(-2);
// Adding +1 because January starts at index 0, not 1
const curr_month = ("0" + (new Date(targetDate).getMonth() + 1)).slice(-2);
const curr_year = new Date(targetDate).getFullYear();

// Output will be in the format: 03-31-2022
console.log(curr_month + "-" + curr_date + "-" + curr_year);

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

On localhost, Angular 2 route parameters are automatically converted to lowercase, while they stay capitalized on the server

I am currently working on a .NET Angular 2 program that has a route set up like this: <ControllerName>/:id While running it on localhost with IIS Express, the id route parameter automatically gets converted to lowercase in the URL without any addi ...

Angular 2 Ahead-of-Time compiler: all clear on the error front, yet a nagging feeling of

I've spent the last 72 hours trying to figure out how to make Ahead-of-Time compilation work for my Angular 2 rc.6 application. Currently, my application runs smoothly using Just-in-Time compilation. I've made sure to install all necessary depe ...

Analyzing elements within an array using Angular 4

I have an array filled with various Objects such as: [ {"id":1,"host":"localhost","filesize":73,"fileage":"2018-01-26 09:26:40"}, {"id":2,"host":"localhost","filesize":21,"fileage":"2018-01-26 09:26:32"}, {...} ] These objects are displayed in the fol ...

A simple method in JavaScript/TypeScript for converting abbreviations of strings into user-friendly versions for display

Let's say I am receiving data from my backend which can be one of the following: A, B, C, D Although there are actually 20 letters that could be received, and I always know it will be one of these specific letters. For example, I would like to map A ...

Transferring all instructions to a subordinate element within the component

I have developed a set of custom directives specifically for <input> elements. Additionally, I have created a custom component called <app-decorated-input>. Within my application, there are numerous instances of both <app-decorated-input> ...

Error message: 'React TypeScript: (props: OwnProps) => Element' cannot be assigned to type 'FunctionComponent<{}>'

Everything seems to be working fine as a JSX element... interface OwnProps { children: JSX.Element; location: Location; } export function Layout(props: OwnProps): JSX.Element { However, when I convert it into a functional component, an error occurs ...

Comparing Angular i18n JSON files automatically for consistency checks

Within my Angular application, I am working with two translation files: en.json and xx.json. While the standard practice is to create translations in both files for a multilanguage application, some developers may only add translations to one file when tes ...

What is the best way to account for the 'elvis operator' within a given expression?

When connecting to my data from Firebase, I noticed that using the elvis operator is essential to avoid encountering undefined errors. Recently, as I delved into creating reactive forms, I encountered an issue with a component I developed that fetches actu ...

Ag-Grid filter not displaying

In my HTML file, I have the following code: <ag-grid-angular #agGrid style="height: 300px" [rowData]="rowData" [columnDefs]="columnDefs" [gridOptions]="gridOptions" ...

Using React Material UI in VSCode with TypeScript significantly hampers autocompletion speed

When including the "@mui/material", Visual Studio Code may become unresponsive, leading to Typescript warnings appearing after 10-15 seconds instead of the usual less than 10 milliseconds. For example: import { Button } from '@mui/material&a ...

Retrieve the property of a Typescript object using a template argument

I am looking to develop a Typescript Collection class that can locate items by field. Here is an example of what I have in mind: class Collection<T, K keyof T> { private _items: T[]; public isItemInCollection(item: T) { return _item ...

The interfaces being used in the Redux store reducers are not properly implemented

My Redux store has been set up with 2 distinct "Slice" components. The first one is the appSlice: appSlice.ts import { createSlice, PayloadAction } from "@reduxjs/toolkit"; import type { RootState } from "./store"; export interface CounterState { value ...

Struggling to understand the usage of FromBody in ASP.NET Core

In my current project, I have a WEB API method that interacts with a SPA template built using Angular: [HttpPost] public IActionResult Post([FromBody]MyViewModel model) After reading a discussion on this topic, I was under the impression that including [ ...

Troubleshooting the failure of chaining functions in Angular2 during an HTTP request

I want to organize functions based on their specific roles in the code Here's the situation: when I'm making an http request, I want to separate the function that handles attaching the access token and headers from the one responsible for actual ...

I'd like some clarification on the code that dynamically adds routes using Typescript and Node Express. Can someone please

Running my API server with node/typescript and express / express validator, I came across this code that I found really useful for separating route logic: function createCustomRouter(route: Array<CustomRouteEntry>): Router { const customRouter = R ...

Creating a channel for communication between sibling components in Angular 4 by storing component references in a shared service

I am searching for a way to establish communication between two sibling Angular 4 components. After reviewing the documentation at https://angular.io/guide/component-interaction, my idea revolves around utilizing a service that stores a reference to the c ...

What prevents `console.log` from working within a button click event?

Why is this not functioning correctly? <button (click)="console.log('ok');">Display Details</button> The error message reads: Cannot read property 'log' of undefined However, a console.log statement in the class construc ...

Storing file paths as string variables in Angular: a quick guide

I'm working with this line of code that selects all the files in a folder. <input type="file" id="filepicker" name="fileList" (change)="saveFolderLocation($event)" webkitdirectory/> My goal is to determin ...

Preventing Button Clicks in Angular 2 When Form Data is Modified

I am looking to determine if at least one field in my form has been altered. When this condition is met, the disableButton variable will be set to true, and false if there are no changes in the form. Here is the snippet of code I am currently using: // Th ...

What is the best way to set up the typeRoots option for proper configuration

I have a unique yarn monorepo structure that is oddly shaped. Here's how it's set up: monorepo root ├── frontend │ ├── dashboard <-- not managed by yarn workspaces │ | ├── src │ | ├── node_modules │ ...