I have an angular project that will be used internationally. In the backend all the dates are managed as timestamps (Date class) and in angular I receive them as Dates. The point is that I need to convert these dates in a "yyyy-MM-dd HH:mm" with the timezone for hours and minutes where the client is being using it, so I should need to read the browser timezone and then convert the date, the point is that I only can achive to get the browser timezoneOffset and I dont know how to convert the Date with and specific timezoneOffset or how to do that.
this.statsServ.getLastDateUpdate().subscribe(
(lastDate : Date) => {
console.log(lastDate);
const timeZoneOffset = new Date().getTimezoneOffset();
console.log(`timezone offset:` timeZoneOffset);
let dateString :string = formatDate(lastDate,"dd-MM-yyyy HH:mm");
console.log(dateString);
}
)
}
lastDate is the received date as Date class I need to format date in this format dd-MM-yyyy HH:mm and according the browser client timezone.
Thanks in advance.
CodePudding user response:
It is hard to give a perfect explanation about your problem without seeing some code, but if i figured right, then it's that you are receiving a UTC date format from backend, and looking to represent it in local time zone, if that's so; then simply pass the date to the Date
class constructor
it would go something like this
const event = new Date('05 October 2011 14:48 UTC');
console.log(event.toString());
// expected output: Wed Oct 05 2011 16:48:00 GMT 0200 (CEST)
// (note: your timezone may vary)
console.log(event.toISOString());
// expected output: 2011-10-05T14:48:00.000Z
Source: developer.mozilla
EDIT:
As i previously referred, inserting date into Date
class constructor
would do the trick for you (It would take host's time zone), so your code would go something like this:
this.statsServ.getLastDateUpdate().subscribe(
(utcDate: Date) => {
console.log(utcDate);
const date = new Date(utcDate);
console.log(date);
}
)
}
And strongly recommend using DatePipe
in your component, it would make your code look cleaner.
DatePipe
usage in .component.html
:
<h1>{{date | date: 'short'}}</h1>
Hope this hepled.