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.
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.
Here's my method: var now = new Date(); var utc = new Date(now.getTime() + now.getTimezoneOffset() * 60000);
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!
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With