1

We are using java as Backend ,in which we use the ISO 8601. To pass the the same I need to convert the date into same format.

in java we use

DateFormat iso8601 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX");

similarly how to convert the date into the very same format in Angular/TypeScript

I'm attaching an Image for your reference for the date format. please see the image.

enter image description here

4 Answers4

1

You need to use DatePipe in your component

app.component.ts

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

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ],
  providers: [DatePipe]
})
export class AppComponent  {
  today;
  constructor(
    private datePipe:DatePipe
  ){
      this.today = this.datePipe.transform( new Date(),'yyyy-MM-dd  h:mm:ssZZZZZ');
  }
}

For any other date-formats check here: https://angular.io/api/common/DatePipe

Working stackblitz example: https://stackblitz.com/edit/angular-datepipe-in-component-u8bzre?file=src/app/app.component.ts

Msk Satheesh
  • 932
  • 1
  • 3
  • 6
1

Please refer the below link, I think it should serve your purpose

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

The toISOString() method returns a string in simplified extended ISO format (ISO 8601)

let today = new Date('05 October 2011 14:48 UTC')

console.log(today.toISOString())  // Returns 2011-10-05T14:48:00.000Z
0

Convert an ISO date to the date format yyyy-mm-dd in JavaScript

For reference, here's what I used. I chose to omit hours, minutes and seconds in my example. It works fine, though. Shouldn't be angular specific, so it should work as vanilla javascript.

var theDate = new Date();
var dd = String(theDate.getDate()).padStart(2, '0');
var mm = String(theDate.getMonth() + 1).padStart(2, '0'); //January is 0!
var yyyy = theDate.getFullYear();

theDate = yyyy + '-' + mm + '-' + dd;
0

I found out how to create the format we want.

we can use the code below to get the desired output.

let date: string = "" 
date = this.datepipe.transform(new Date(), "yyyy-MM-ddThh:mm:ssZZZZZ")

you can also substitute new Date() with your date variable.

enter image description here