2

I am looking for a javascript function to convert UTC datetime to a passing timezone's datetime format. I have to pass the timezone as per user's location. I am not allowed to use any date library.

my UTC datetime string : "2016-04-10 09:00:00.0"

Passing Timezone :EST

Expected Output1 : "April 10,2016"

Expected Output2 : 04 AM EST

Can you give some insight about the Js function to acheive my requirement?

P.S: I can't use any third party date library for this work.

user5970552
  • 173
  • 2
  • 14
  • 1
    You should show what you have tried, this isn't a free coding service. If this is homework or an assignment, you should say so. Your string is not consistent with any standard, you need to parse it manually (2 lines of code). Adjusting to a particular timezone simply requires modifying the time by an appropriate amount. There are many questions and answers here on how to do that. Search, try something, post again if it doesn't work. – RobG Mar 03 '16 at 23:51

2 Answers2

0

You can create a function like below to convert an UTC time to a given time zone offset:

//function to calculate local time
function calcTime(datestring, city, offset) {

  d = new Date(datestring);

  utc = d.getTime() + (d.getTimezoneOffset() * 60000);

  nd = new Date(utc + (3600000 * offset));

  var options = {}
    // an application may want to use UTC and make that visible
  options.timeZone = 'America/' + city;
  options.timeZoneName = 'short';

  return nd.toLocaleString('en', options)


}


document.write('Local time on server: 2016-04-10T09:00:00' + '<br>')
document.write('Local time in EST/EDT:' + calcTime('2016-04-10T09:00:00', 'New_York', '-5.0'));

If you only have to support different time zones in the US, you could create a look up table matching the time zone offset to the correct city

Eastern ........... America/New_York
Central ........... America/Chicago
Mountain .......... America/Denver
Mountain no DST ... America/Phoenix
Pacific ........... America/Los_Angeles
Alaska ............ America/Anchorage
Hawaii ............ America/Adak
Hawaii no DST ..... Pacific/Honolulu

As you can see the logic quickly becomes complex and therefore is better to use external libraries where possible.

Alex
  • 21,273
  • 10
  • 61
  • 73
0

i use this time management, try maybe your you are looking for this

Moment.js