0

Given inputs

1) Datetime : day month year hh and mins

2) Timezone

How to create a Javascript date object of a specific time zone or date in UTC ?

Also how to convert this date time to any other timezone.

Is there any package in angular that can do this.

1 Answers1

0

So I do it like this:

var offset = -5.0; // my servers UTC offset

var clientDate = new Date();
var utc = clientDate.getTime() + (clientDate.getTimezoneOffset() * 60000);

var serverDate = new Date(utc + (3600000 * offset));
var c = $.datepicker.formatDate('mm/dd/yy', serverDate);

In the last line, I use the jQuery (commonly called BootStrap) datepicker to format the date for me.

The key here is offset which is the hours offset from UTC time.

In Angular you can use dateFilter

 new Date(dateFilter(minDate, 'yyyy-MM-dd\'T\'00:00:00', timezone));
Alexander Higgins
  • 6,765
  • 1
  • 23
  • 41
  • Can this be done in angular may be using another package – Vineet Rawat Jul 08 '17 at 03:38
  • Angular has the dateFilter. And yes, its pure JavaScript. But i have seen angular templates implementing this same approach. – Alexander Higgins Jul 08 '17 at 04:15
  • Sorry, but this code is flawed in several places. Understand that the timestamp returned from `.getTime()` is *already* in UTC. By adjusting it with the client's current offset, you're just picking a different point in time. Same thing when you try to add the server's offset as an input to the `Date` constructor. One cannot get the `Date` object to represent a different time zone by shifting the offset in this manner. It will still format output based on the local time of the machine it's running on, including DST changes for that time zone. – Matt Johnson-Pint Jul 08 '17 at 22:00
  • Also, you can't assume that your server's offset is -5, it may be that right now, but it can easily switch to a different offset when a DST transition occurs. And lastly, it's a bad practice to write code that's dependent on a server's time zone at all. Sorry for the downvote, but this code should not propagate. – Matt Johnson-Pint Jul 08 '17 at 22:01
  • The term for adjusting the utc-based timestamp by an offset is called "epoch shifting". It's a useful technique, used by many date libraries, but it's only acceptable if from that point forward you *only* use the UTC-based functions, like `.getUTCFullYear()`, etc. Any use of local time functions (which the datepicker's date formater is doing) is going to hit errors around DST transitions. – Matt Johnson-Pint Jul 08 '17 at 22:04
  • Yep, thats why my `var offset = -5.0` is set from the server itself. clientData.getTimezoneOffset() will get me the correct offset on the client. and the datepicker's date format is used only to force the date into a MM/DD/YYYY format. – Alexander Higgins Jul 08 '17 at 22:50