Reputation: 1400
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;
}
Upvotes: 7
Views: 73729
Reputation: 3719
You can use toISOString()
function (MDN web docs).
The timezone is always zero UTC offset.
const activationDate = new Date().toISOString();
Upvotes: 14
Reputation: 609
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
],
Upvotes: 3
Reputation: 1400
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
Upvotes: 15
Reputation: 2078
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());
Upvotes: 2