
The timestamp
is a Unix timestamp in milliseconds format used to hold a date and time.
It holds the number of milliseconds from 1970-01-01.
It is a 10-digit number. a timestamp is a long number in seconds from 1970 JANUARY 1 UTC format.
For example, the Timestamp is 1587143959831.
This blog post explains how to convert a timestamp to a date format in multiple ways.
The Date
object in javascript holds the Date and time format. example date format is 25-11-2021 10:06:02;
This post talks about the Date format only.
You can also check my other related post
Following are ways to convert Unix timestamp to Date format.
- Javascript/Typescript convert timestamp to Date format
- Angular timestamp to Date.
- MomentJS
As you know you can get the current timestamp in javascript as seen below Here is a code for How to get the timestamp in Javascript?
let currentDate=new Date(); // 2020-04-17T17:19:19.831Z
console.log(currentDate.getTime()) //1587143959831
Let us consider the Unix timestamp given in the string as follows.
let timestamp=1587143959831;
How to convert timestamp string to Date format YYYY-DD-MM Typescript
Date
is an inbuilt object in javascript, which provides the toLocaleDateString() method
to return date format for given ISO consider
In the below en-us
is the 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.
How to convert timestamp to date format in Angular using MomentJS code?
MomentJS
is a third-party utility library for the manipulation of Date and time in javascript applications.
It is very easy to do if the moment is already used in the application.
Here is an example code
const date = moment(timestamp).format('L');
console.log(date); // 4/17/2020
Angular example to convert timestamp to Date object
In angular applications, many ways we can do it
- Pipes
- typescript
Pipes can be used in angular HTML templates We can write Typescript code in Angular typescript components.
pipes
In the typescript, the timestamp variable is declared with the value. Here is the syntax of the pipe symbol
{{timestamp | date::dateformat}}
the timestamp is of number type which holds many mill seconds Date format encloses in single quotes with a format like ‘YYYY-DD-MM HH: SS’
In the 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 the component template HTML filter, using pipe symbol, with date attribute, the date format is declared.
<div>{{score.timestamp | date:'dd/MM/yyyy'}}</div>
Output:
17/04/2020
Conclusion
In this example, You learned multiple ways to convert timestamp to date format in Angular and typescript code with examples