Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript -- get current date using UTC offset

How can I get the current date based on UTC Offset? For example, the UTC Offset for Australia is UTC +10:00 where it is already May 24th.

I can get UTC date and hour but can't find any Date methods that factor in UTC Offset.

like image 251
stackato Avatar asked May 23 '16 19:05

stackato


People also ask

Is new date () getTime () UTC?

Use the getTime() method to get a UTC timestamp, e.g. new Date(). getTime() . The method returns the number of milliseconds since the Unix Epoch and always uses UTC for time representation.

How can I get the current date and time in UTC or GMT in JavaScript?

Here's my method: var now = new Date(); var utc = new Date(now.getTime() + now.getTimezoneOffset() * 60000);

How do you find the date and time in UTC?

Use the toUTCString() method to get the current date and time in utc, e.g. new Date(). toUTCString() . The toUTCString method converts a date to a string using the UTC time zone. Copied!

How do I get current time zone in JavaScript?

The JavaScript getTimezoneOffset() method is used to find the timezone offset. It returns the timezone difference in minutes, between the UTC and the current local time. If the returned value is positive, local timezone is behind the UTC and if it is negative, the local timezone if ahead of UTC.


1 Answers

Once you have the offset (in this case 10 hours) use this function:

function getDateWithUTCOffset(inputTzOffset){
    var now = new Date(); // get the current time

    var currentTzOffset = -now.getTimezoneOffset() / 60 // in hours, i.e. -4 in NY
    var deltaTzOffset = inputTzOffset - currentTzOffset; // timezone diff

    var nowTimestamp = now.getTime(); // get the number of milliseconds since unix epoch 
    var deltaTzOffsetMilli = deltaTzOffset * 1000 * 60 * 60; // convert hours to milliseconds (tzOffsetMilli*1000*60*60)
    var outputDate = new Date(nowTimestamp + deltaTzOffsetMilli) // your new Date object with the timezone offset applied.

    return outputDate;
}

In your case you would use:

var timeInAustralia = getDateWithUTCOffset(10);

This will return a Date object. You still need to format the date to your liking.

I agree with @Frax, Moment is a great library if you don't mind adding additional dependencies to your project.

Good luck

like image 123
victmo Avatar answered Sep 22 '22 08:09

victmo