user11364823
user11364823

Reputation:

Convert timestamp date into proper date format with month name

Need to convert below timestamp date

var uploadDate = 2021-04-17T17:19:19.831Z

into proper date format with month name also like this - 04 Feb 2021

in .ts file. I don't need that in html

How to get this.uploadDate = 04 Feb 2021 like this.

Upvotes: 1

Views: 4731

Answers (4)

phuzi
phuzi

Reputation: 13060

In Angular you can format a date like string using the date filter from CommonModule

Inside your component:

this.myDate = "2021-04-17T17:19:19.831Z";

And in the view use the date filter to format the date however you like

{{ myDate | date: 'dd MMM yyyy'}}

This will give you:

17 Apr 2021

There's a working example over at Stackblitz

Format date inside a Component

You can also use the date pipe inside your component, inject it as you would any other dependency.

Include DatePipe in your module

import { DatePipe } from "@angular/common";

@NgModule({
  ...
  providers: [DatePipe]
})
export class AppModule {}

Add it to your component's dependencies:

import { DatePipe } from '@angular/common';

Inside your component add the dependency to your class:

constructor(private datePipe: DatePipe) {}

And then you are free to format a date inside your component:

this.datePipe.transform(this.date, "dd MMM yyyy")

Upvotes: 2

Udyan Sharma
Udyan Sharma

Reputation: 134

Using Vanilla Js we can use the toDateString() and tweak it's result a bit, to get the desired result, I am not aware about if this is the best way w.r.t angularjs

    let dateArr = new Date("2021-04-17T17:19:19.831Z").toDateString().split(" "); // the array would look like [ 'Sat', 'Apr', '17', '2021' ]
    dateArr.shift();  // removes the day(Sat) from the array
    console.log(dateArr.join(" ")); // Output: Apr 17 2021

Upvotes: 0

Dmitry Vdovichenko
Dmitry Vdovichenko

Reputation: 21

Sure, you can:

// first get Date from string
const getDateFromStr = (dateString) => new Date(Date.parse(dateString));
// setting options to format your Date
const dayFormatter = new Intl.DateTimeFormat('en', {
    day: 'numeric',
    month: 'short',
    year: 'numeric',
});
// format your Date
dayFormatter.format(getDateFromStr('2021-04-17T17:19:19.831Z'));

Here you can find more about Intl.DateTimeFormat:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat

And here about Date.parse

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/parse

Upvotes: 0

Uttam Patel
Uttam Patel

Reputation: 1

var uploadDate = "2021-04-17T17:19:19.831Z";
var monthNames = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
var d = new Date(uploadDate);
var month = monthNames[d.getMonth()];
var day = String(d.getDate()).padStart(2, '0');
var year = d.getFullYear();
var formatedDate = day  + ' '+ month + ' ' + year;
console.log(formatedDate);

Upvotes: 0

Related Questions