7

I have a request from angular, which sends date to server.

const activationDate = new Date();

I need to convert this to UTC date format before sending the request

In my model, I have a Date variable to pass the date to server

export class PersonDetails {
  id: string;
  activationDate?: Date;
}

4 Answers 4

15
personModel: PersonDetail;    

const activationDate = new Date();

this.personModel.activationDate = new Date(activationDate.getUTCFullYear(),
                                            activationDate.getUTCMonth(),
                                            activationDate.getUTCDate(),
                                            activationDate.getUTCHours(),
                                            activationDate.getUTCMinutes(),
                                            activationDate.getUTCSeconds()
                                            );

OR Can use a separate method to get UTCDate

const activationDate = this.getNowUTC();    

private getNowUTC() {
  const now = new Date();
  return new Date(now.getTime() + (now.getTimezoneOffset() * 60000));
}

A good article on converting DateTime

Sign up to request clarification or add additional context in comments.

Comments

14

You can use toISOString() function (MDN web docs).

The timezone is always zero UTC offset.

const activationDate = new Date().toISOString();

Comments

3

I created a pipe like this

@Pipe({ name: 'UTCDate'})
export class UTCDatePipe implements PipeTransform  {
    constructor() {}
    transform(value) {
        if (value)  {
            return  moment.utc(value).format('YYYY MMMM DD');
        } else {
              return '';
        }
    }
}

And view like this:

{{invoice.invoiceDate | UTCDate}}

and to this app.module

import {UTCDatePipe} from "@app/utcDate.component";

@NgModule({
    declarations: [
        AppComponent,
        UTCDatePipe
    ],

Comments

2

Although the above solutions are correct if you need to play with the date a lot you can use moment.js lib which might be really helpful.

Refer http://momentjs.com/docs/#/parsing/utc/ for more.

1. npm install moment
2. import * as _moment from 'moment';
const moment = _moment;
const utcDate = moment.utc();
console.log(utcDate.format());

2 Comments

Moment has been deprecated, themselves recommend not to use it anymore.
This answer was posted 2 years back

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.