surazzarus
surazzarus

Reputation: 792

Change the data and time format

I am using owl-date-time to get the date and time in angular.

It returns the data and time format as: 2018-08-20T07:37:09.000Z

Is there a way that I can modify the format as: 2018-08-20 09:37

Any help is apprecitated.

Upvotes: 4

Views: 5620

Answers (3)

Niladri Basu
Niladri Basu

Reputation: 10624

I know it's a bit overkill but you can use moment.js like this:

console.log(new moment(`2018-08-20T07:37:09.000Z`).format('YYYY-MM-DD hh:mm'));
<script src="https://momentjs.com/downloads/moment.js"></script>

However, if you want your output string to be exactly alike do something like this:

let input = '2018-08-20T07:37:09.000Z';

let date = new moment(input).format('YYYY-MM-DD');

let time = (a => `${a[2]}:${a[1]}`)(input.split('T')[1].split(':').map(s => s.slice(0,2)));

console.log(`${date} ${time}`);
<script src="https://momentjs.com/downloads/moment.js"></script>

Upvotes: 0

DEVCNN
DEVCNN

Reputation: 622

As stated by others, moment.js is an overkill.For just formatting purpose, you could use plain javascript.

time = new Date('2018-08-20T07:37:09.000Z').toLocaleString().split(',')[1];
console.log(time)
time = time.split('').splice(0,6).join('');
date  ='2018-08-20T07:37:09.000Z'.split('T')[0];
console.log(date + time)

Upvotes: 0

FK82
FK82

Reputation: 5075

There is a momentjs integration:

npm install ng-pick-datetime-moment moment --save

Having done that, you can use moment format strings in OWL_DATE_TIME_FORMATS. An example from the docs:

import { NgModule } from '@angular/core';
import { OwlDateTimeModule, OWL_DATE_TIME_FORMATS} from 'ng-pick-datetime';
import { OwlMomentDateTimeModule } from 'ng-pick-datetime-moment';

// See the Moment.js docs for the meaning of these formats:
// https://momentjs.com/docs/#/displaying/format/
export const MY_MOMENT_FORMATS = {
    parseInput: 'l LT',
    fullPickerInput: 'l LT',
    datePickerInput: 'l',
    timePickerInput: 'LT',
    monthYearLabel: 'MMM YYYY',
    dateA11yLabel: 'LL',
    monthYearA11yLabel: 'MMMM YYYY',
};

@NgModule({
    imports: [OwlDateTimeModule, OwlMomentDateTimeModule],
    providers: [
        {provide: OWL_DATE_TIME_FORMATS, useValue: MY_MOMENT_FORMATS},
    ],
})
export class AppExampleModule {
}

The format you are looking for is 'YYYY-MM-DD HH:mm':

console.log(moment().format('YYYY-MM-DD HH:mm'))
<script src="https://momentjs.com/downloads/moment.js"></script>

Upvotes: 0

Related Questions