Skip to content

Instantly share code, notes, and snippets.

@franciscojsc
Created September 25, 2025 01:59
Show Gist options
  • Select an option

  • Save franciscojsc/09eb726590f171fbc9be67af547423e9 to your computer and use it in GitHub Desktop.

Select an option

Save franciscojsc/09eb726590f171fbc9be67af547423e9 to your computer and use it in GitHub Desktop.
Returns the current date and time in UTC, with an optional offset in hours
/*
* Returns the current date and time in UTC, with an optional offset in hours.
* If no offset is provided, it defaults to 0 (UTC time).
* Example usage:
* nowUTC();
* nowUTC(3); // UTC+3
* nowUTC(-5); // UTC-5
* nowUTC(0); // UTC
* nowUTC(1.5); // UTC+1:30
* nowUTC(-2.5); // UTC-2:30
* nowUTC(14); // UTC+14
* nowUTC(-12); // UTC-12
*/
function nowUTC(offset) {
if (typeof offset === "undefined") {
offset = 0; // Default to UTC if no offset is provided
}
var date = new Date();
var utc_timestamp = Date.UTC(
date.getUTCFullYear(),
date.getUTCMonth(),
date.getUTCDate(),
date.getUTCHours(),
date.getUTCMinutes(),
date.getUTCSeconds(),
date.getUTCMilliseconds()
);
return new Date(utc_timestamp + offset * 3600 * 1000);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment