Shubham Singh
Shubham Singh

Reputation: 147

How to convert Current date as a Date datatype in typescript or javascript

I am using the Below function to generate the Date and Time in my angular app but it's returning as a string instead of date&time dataType.

getCurrentDateAndTime() {
  const today = new Date();
  const datePipe = new DatePipe('en-IN');
  return datePipe.transform(today, 'dd/MM/yyyy, hh:mm a');
}

can suggest doing better way for generating Date datatype in the format 'dd/mm/yyyy , hh:mm am'

Upvotes: 0

Views: 1570

Answers (3)

praga2050
praga2050

Reputation: 773

May be another way using getTime()You have to use ISO only. See this Stackoverflow Link

What is the "right" JSON date format?

import { DatePipe } from "@angular/common";
import { Component, VERSION } from "@angular/core";

@Component({
  selector: "my-app",
  templateUrl: "./app.component.html",
  styleUrls: ["./app.component.css"],
  providers: [DatePipe]
})
export class AppComponent {
  name = "Angular " + VERSION.major;

  dataFormatted: string = "";
  dateInMilliSecond: number;
  dataISO: string = '';

  constructor(protected datePipe: DatePipe) {}

  ngOnInit() {
    const today = new Date();
    const datePipe = new DatePipe("en-IN");
    this.dataFormatted = datePipe.transform(today, "dd/MM/yyyy, hh:mm a");
    this.dateInMilliSecond = new Date().getTime();
    this.dataISO = new Date().toISOString();
  }
}


{{dataFormatted}}
<br/>
<br/>
In MilliSecond: {{dateInMilliSecond | date: 'dd/MM/yyyy, hh:mm a'}}
<br/>
<br/>

ISO Date : {{dataISO}}

Upvotes: 0

Benny Halperin
Benny Halperin

Reputation: 2322

Date type value is numeric internally. The string representation can vary according to your choice. In your case:

const d = new Date();
const dAsString = d.toLocaleString('en-IN');

Result: "23/12/2020, 8:46:27 am"

Upvotes: 0

Bernhard
Bernhard

Reputation: 1273

Why are you using the datePipe.transform method? It's job is to create a string for representation so if you want a Date returned, you don't need the datePipe, you can just return new Date() (ofc you don't need a method for that)

Regarding your edit, you don't keep date objects in a specific format, it just keeps the information about the point in time, you usually only apply a format once you want to display it and that's when the datePipe.transform method comes into play.

Upvotes: 1

Related Questions