How to set date always to eastern time regardless of user's time zone

前端 未结 3 1598
甜味超标
甜味超标 2020-12-10 11:56

I have a date given to me by a server in unix time: 1458619200000

NOTE: the other questions you have marked as \"duplicate\" don\'t show how to get there fro

相关标签:
3条回答
  • 2020-12-10 12:01

    For dayLight saving, Eastern time become 4 hours behind UTC thats why its offset is -4x60 = -240 minutes. So when Day light is not active the offset will be -300. easternTimeOffset variable value is the key point to be noted here. Kindly see this code in action in attached image.

           var offset = new Date().getTimezoneOffset();// getting offset to make time in gmt+0 zone (UTC) (for gmt+5 offset comes as -300 minutes)
            var date = new Date();
            date.setMinutes ( date.getMinutes() + offset);// date now in UTC time
    
            var easternTimeOffset = -240; //for dayLight saving, Eastern time become 4 hours behind UTC thats why its offset is -4x60 = -240 minutes. So when Day light is not active the offset will be -300
            date.setMinutes ( date.getMinutes() + easternTimeOffset);
    

    0 讨论(0)
  • 2020-12-10 12:10

    You can easily take care of the timezone offset by using the getTimezoneOffset() function in Javascript. For example,

    var dt = new Date(1458619200000);
    console.log(dt); // Gives Tue Mar 22 2016 09:30:00 GMT+0530 (IST)
    
    dt.setTime(dt.getTime()+dt.getTimezoneOffset()*60*1000);
    console.log(dt); // Gives Tue Mar 22 2016 04:00:00 GMT+0530 (IST)
    
    var offset = -300; //Timezone offset for EST in minutes.
    var estDate = new Date(dt.getTime() + offset*60*1000);
    console.log(estDate); //Gives Mon Mar 21 2016 23:00:00 GMT+0530 (IST)
    

    Though, the locale string represented at the back will not change. The source of this answer is in this post. Hope this helps!

    0 讨论(0)
  • 2020-12-10 12:10

    Moment.js (http://momentjs.com/timezone) is your friend.

    You want to do something like this:

    var d = new Date(1458619200000);
    var myTimezone = "America/Toronto";
    var myDatetimeFormat= "YYYY-MM-DD hh:mm:ss a z";
    var myDatetimeString = moment(d).tz(myTimezone).format(myDatetimeFormat);
    
    console.log(myDatetimeString); // gives me "2016-03-22 12:00:00 am EDT"
    
    0 讨论(0)
提交回复
热议问题