3 ways to convert timestamp string to Date format example - Angular|Typescript|javascript


In this blog article, you’ll learn ways to convert timestamp to Date format.

convert timestamp string to Date

timestamp is a unix format used to holds date and time and It is 10 digit number.

How to get the timestamp in Javascript

let currentDate=new Date(); // 2020-04-17T17:19:19.831Z
console.log(currentDate.getTime()) //1587143959831

So timestamp is long number in seconds from 1970 JANUARY 1 utc format. Date object in javascripts holds Date and time format. This posts talks about Date format only.

In the below post, You’ll learn many ways to convert unix timestamp to Date format -javascript/Typescript convert timestamp to Date format -Angular timestamp to Date -MomentJS

Let us consider the unix timestamp given in straing as follows

let timestamp=1587143959831;

Typescript example - convert to Date format -YYYY-DD-MM

Date inbuilt in javascript provides toLocaleDateString() method to return date format for give ISO consider In the below en-us is USA date format provided

var date = new Date(timestamp).toLocaleDateString("en-us")
console.log(date) //4/17/2020

The same code works in javascript also

MomentJS library

if momentjs already using in application, It is very easy to do .

MomentJS is date thirdparty library for javascript applications.

const date = moment(timestamp).format('L');
console.log(date); // 4/17/2020

Angular example

In angular applications, many ways we can do it

  • Pipes
  • typescript

pipes

In the typescript, timestamp variable is declared with value

In typescript code component

import { Component } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
 timestamp=1587143959831;
}

In component template html filter, using pipe symbole, with date attribute, date format is declared.

<div>{{score.timestamp | date:'dd/MM/yyyy'}}</div>

Output is

17/04/2020
Similar Posts