Is it possible to generate a Date object from a predetermined string in typescript?

I have a string with values separated by commas, and I'm trying to create a Date object from it. It seems like this is not doable -- can someone verify this and provide a solution if possible?
This code snippet doesn't work :

let dateString='2017,3,22,0';
let dateFromString = new Date(dateString);

However, this code works fine (when passing individual numbers) :

let dateFromString = new Date(2017,3,22,0);

And this code also works :

let dateString = '2008/05/10 12:08:20';
let dateFromString = new Date(dateString);

The objective is to generate a Date object from a consistent string format. Is there a way to achieve this?

Can I generate a Date object from a standard string that uses only one type of separator (comma, colon, slash, etc.)?

Answer №1

If your coding environment supports ES6 (e.g. Babel, TypeScript, up-to-date Chrome/Firefox), you have the option to utilize the .split(',') method on strings to split them into arguments as shown below:

const dateString = '2019,8,15,0';
const date = new Date(...dateString.split(','));  // creates a date object for August 15, 2019

For compatibility with ES5, you can use the following approach:

var dateString = '2019,6,7,0';
var date = new (Function.prototype.bind.apply(Date, [null].concat(dateString.split(','))));

To understand how the .bind.apply technique functions in conjunction with new, refer to this insightful discussion: Use of .apply() with 'new' operator. Is this possible?

Note: A big thank you to the helpful feedback provided by the commenters below 👍

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

Step-by-step guide on adding a command to a submenu through the vscode extension api

I'm developing a Visual Studio Code extension and I want to include a command in a submenu like this https://i.stack.imgur.com/VOikx.png In this scenario, the "Peek" submenu contains commands such as "Peek Call Hierarchy". My current Package.json fi ...

Unlocking the potential: passing designated text values with Javascript

In my current React code, I am retrieving the value from cookies like this: initialTrafficSource: Cookies.get("initialTrafficSource") || null, Mapping for API const body = {Source: formValue.initialTrafficSource} Desired Output: utmcsr=(direct)|utmcmd=(n ...

Tips on exporting a basic TypeScript class in an Angular 4 module

I am facing a challenge with packaging a TypeScript class as part of an Angular module for exporting it as a library using ng-packagr. For instance, here is my class definition - export class Params { language: string ; country: string ; var ...

What advantages does CfnAppSync provide over using AppSync in a CDK project?

We are in the process of enhancing our API by adding new JS resolvers and phasing out the VTL resolvers for an AWS AppSync CDK project, specifically built with Cfn<> Cloud Front CDK. The code snippet below illustrates how this can be achieved: ...

Data that changes dynamically on a chart

When making a rest call to fetch data, I aim to populate the pieChartData with the obtained information. However, I am facing difficulties in achieving this task. Can someone guide me on how to accomplish this? import { Component, OnInit} from '@angu ...

The absence of the function crypto.createPrivateKey is causing issues in a next.js application

For my next.js application, I am utilizing the createPrivateKey function from the crypto module in node.js. However, I encountered an issue as discussed in this thread: TypeError: crypto.createPrivateKey is not a function. It seems that this function was a ...

Tips for scrolling ion-items vertically to the bottom and top using arrow icons in Ionic 4

I'm developing an Ionic 4 app with Angular and looking to incorporate Up and Down Arrow buttons for vertical scrolling from top to bottom and vice versa. ...

Ways to add items to an array adjacent to items sharing a common property value

I have an array consisting of various objects const allRecords = [ { type: 'fruit', name: 'apple' }, { type: 'vegetable', name: 'celery' }, { type: 'meat', name: 'chi ...

We could not find the requested command: nodejs-backend

As part of my latest project, I wanted to create a custom package that could streamline the initial setup process by using the npx command. Previously, I had success with a similar package created with node.js and inquirer. When running the following comma ...

Encountered difficulty retrieving properties from the req.query object within expressjs

My setup includes a router configuration like this: router.get('/top-5-cheap', aliasTopTours, getAllTours); I've also implemented some middlewares: Middleware aliasTopTours: In this middleware, I am setting certain properties on the reque ...

A Project built with React and TypeScript that includes code written in JavaScript file

Is it an issue when building a React project with Typescript that includes only a few JS components when moving to production? ...

Ignore any information in NestJS that is not included in the data transfer object

In my NestJS controller, I have defined a route for updating locality information. The structure of the controller method is as follows: @Put('/:id') updateLocalityInfo( @Query('type') type: string, @Body() data: EditLocalityD ...

Angular 2: Musing on the potential of Hot Module Replacement and the power of @ngrx/store

If you're just getting started, this link might be helpful: understanding the purpose of HMR. When it comes to managing and designing large projects, I'm still in the early stages and haven't grown a wise beard yet. So, I'm seeking adv ...

The 'string' Type in Typescript cannot be assigned to the specified type

Within the fruit.ts file, I've defined a custom type called Fruit which includes options like "Orange", "Apple", and "Banana" export type Fruit = "Orange" | "Apple" | "Banana" Now, in another TypeScript file, I am importing fruit.ts and trying to as ...

Ways to address the error in typescript: "Namespace 'fastify' not found"?

Recently, I made the decision to update all of the packages on my fastify-server template. Upon inspection, my package.json file appears as follows: { "name": "backend-template", "version": "1.0.0", &quo ...

Creating a variable that is not defined and then converting it into

I have an issue with a function that returns an Observable. The problem is that when the function is called, the parameter works fine, but its value becomes undefined within the Observable. This is the function in question: import {Observable} from &apos ...

From integrating Vue 2 TSX to React TSX: ensuring seamless cooperation

Currently, my app is built with Vue 2 using vue-tsx-support, vue-class-component, and vue-property-decorator. All of my Vue 2 components are already TSX classes. I am interested in gradually transitioning to React. I experimented with https://github.com/ ...

In a Custom Next.js App component, React props do not cascade down

I recently developed a custom next.js App component as a class with the purpose of overriding the componentDidMount function to initialize Google Analytics. class MyApp extends App { async componentDidMount(): Promise<void> { await initia ...

What is the most efficient way to calculate the number of days between today's date and May 20, 2011 using PHP?

Similar Question: How can I calculate the number of days between two dates using PHP? I've seen a JavaScript solution, but I'm looking for a PHP alternative. Any suggestions? ...

Angular 2 TypeScript: Accelerating the Increment Number Speed

I'm working with a function in Angular 4 that is triggered when the arrow down key is pressed. Each time the arrow down key is hit, the counter increments by 1. In this function, I need to run another function if the counter reaches a certain speed. ...