Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert UTC date/time to EST date/time

I'm using the following code to get the current UTC time in the correct format, but the client has come back and asked that the timestamp now be in EST instead of UTC. I have searched Google and stackoverflow, but can't find an answer that works with my existing code.

var currentdate = new Date(); 
var datetime = currentdate.getFullYear() + ":"
            + ("0" + (currentdate.getUTCMonth()+1)).slice(-2) + ":"
            + ("0" + currentdate.getUTCDate()).slice(-2) + ":"
            + ("0" + currentdate.getUTCHours()).slice(-2) + ":"  
            + ("0" + currentdate.getUTCMinutes()).slice(-2) + ":" 
            + ("0" + currentdate.getUTCSeconds()).slice(-2);

What we are trying to do is set a consistent timestamp to EST regardless of where the browser is located in the world, hence the use of the UTC time originally.

Thanks!

like image 878
Andrew R Avatar asked Jan 07 '14 07:01

Andrew R


1 Answers

A few things...

  • The term "EST" can be used for either Eastern Standard Time in North America, or Eastern Standard Time in Australia. Most time zone abbreviations are not unique, so you should be more specific.

  • EST also does not define a time zone in its entirety. It only defines part of the time zone that is used during the winter months. The other half is called Eastern Daylight Time, abbreviated EDT. Your client probably meant "Eastern Time", which would need to take both into account.

  • The typical way to define time zones is as an identifier from the IANA time zone database. You can read more about it in the timezone tag wiki. For example, if your client meant Eastern Time in the United States, then your time zone is "America/New_York".

  • JavaScript inherently doesn't know anything about time zones, other than it's own and UTC. (The link that bjb568 gave does not handle daylight saving time properly.) In order to work with them on the client, you will need to use one of the libraries I list here.

  • Your current code is a bit strange in terms of output. Usually colons are used for separating only the time, and you are using them for all parts. Anyway, it's not converting anything, it's just outputting UTC.

  • You might do well with a library like moment.js and it's moment-timezone add-on. For example:

    moment().tz("America/New_York").format("YYYY-MM-DD HH:mm:ss")
    
like image 179
Matt Johnson-Pint Avatar answered Oct 16 '22 12:10

Matt Johnson-Pint