Ad/iklan :

3gp Mp4 HD
Play/Download
Live 3D App
Search.Pencarian Menu

Add text send email to rh3252705.adda@blogger.com or Click this (Text porn Will delete) | Tambah teks kirim email ke rh3252705.adda@blogger.com atau Klik ini (Teks porno akan dihapus)
Total post.pos : 17047+

[Go Make Things] Getting a date in the current user's timezone with JavaScript

Last week, a friend of mine nerd-sniped me into an interesting challenge.

An API they're using returns the date as a string in a fixed timezone (in their case, Denver, Colorado, USA), like this…

let dateFromAPI = '2025-01-31T11:50:15';  

And they wanted to display it as a formatted string in the current user's local time.

JavaScript makes this a lot harder than it should be. Today, I wanted to show you the solution I whipped up.

Let's dig in!

Creating a helper function

Let's start by creating a helper function. We'll accept the dateStr to convert and the serverTimezone that date string is in as arguments.

The function will return a new Date() object with that date string adjusted to the user's local timezone.

/**   * Get a date object in the current user's timezone   * @param  {String} dateStr        A date string saved in a specific timezone   * @param  {String} serverTimezone The timezone the dateStr is in   * @return {Date}                  A date object, adjusted to user's timezone   */  function getDateInCurrentUsersTimezone (dateStr, serverTimezone) {  	// Code will go here...  }  

Working with timestamps

In an ideal world, the API would send back a Unix timestamp—a string representing the number of milliseconds since January 1st, 1970, at midnight UTC.

In coding, a Unix timestamp is a nice universal constant for working with dates.

In order to do the math we need to do, we're going to need them. I'll be using very verbose variable names for clarity. Feel free to adjust them.

Finding the offset

We want to get the offset in milliseconds between the server's timezone and the user's timezone.

First, we'll use the new Date() constructor and Date.prototype.toLocaleString() method to get the Date right now, and convert it to a formatted string in the server's timezone.

/**   * Get a date object in the current user's timezone   * @param  {String} dateStr        A date string saved in a specific timezone   * @param  {String} serverTimezone The timezone the dateStr is in   * @return {Date}                  A date object, adjusted to user's timezone   */  function getDateInCurrentUsersTimezone (dateStr, serverTimezone) {    	// Get timezone offsets  	// This gets the difference in ms between the server time and the users current location  	let nowAsStringInServerTimezone = new Date().toLocaleString('en-US', {timeZone: serverTimezone});  	  }  

Let's say it was 1:30pm US Eastern when you that code. Denver is two hours behind the US East Coast.

It will return something that looks like this: '1/31/2025, 11:30:00 AM'.

Now we have a date string for right now that's adjusted to the server's timezone. We'll pass that back into new Date() to create a new Date object, and run the getTime() method on it to get a Unix timestamp.

// Get timezone offsets  // This gets the difference in ms between the server time and the users current location  let nowAsStringInServerTimezone = new Date().toLocaleString('en-US', {timeZone: serverTimezone});  let serverTimestamp = new Date(nowAsStringInServerTimezone).getTime();  

Next, we'll use the Date.now() method to get a Unix timestamp for right now in the current user's timezone.

Then, we'll subtract the serverTimestamp from it to get the different in milliseconds between the two timezones.

// Get timezone offsets  // This gets the difference in ms between the server time and the users current location  let nowAsStringInServerTimezone = new Date().toLocaleString('en-US', {timeZone: serverTimezone});  let serverTimestamp = new Date(nowAsStringInServerTimezone).getTime();  let userTimestamp = Date.now();  let offset = userTimestamp - serverTimestamp;  

Adjusting the date string

Now that we have an offset between the two timezones, we can do our conversion.

We'll pass the dateStr from the server into new Date(), then run the Date.prototype.getTime() method on it to get our Unix timestamp. Then, we'll add the offset to it to adjust the server-based date string to the user's local time.

// ...  let offset = userTimestamp - serverTimestamp;    // Get a unix timestamp for the server date and add the offset  let adjustedTimestamp = new Date(dateStr).getTime() + offset;  

Finally, we'll pass that adjustedTimestamp into one last new Date(), and return it.

// Get a unix timestamp for the server date and add the offset  let adjustedTimestamp = new Date(dateStr).getTime() + offset;    // Return a date object adjusted for the user's timezone  return new Date(adjustedTimestamp);  

The finished function

Here's the complete helper function…

/**   * Get a date object in the current user's timezone   * @param  {String} dateStr        A date string saved in a specific timezone   * @param  {String} serverTimezone The timezone the dateStr is in   * @return {Date}                  A date object, adjusted to user's timezone   */  function getDateInCurrentUsersTimezone (dateStr, serverTimezone) {    	// Get timezone offsets  	// This gets the difference in ms between the server time and the users current location  	let nowAsStringInServerTimezone = new Date().toLocaleString('en-US', {timeZone: serverTimezone});  	let serverTimestamp = new Date(nowAsStringInServerTimezone).getTime();  	let userTimestamp = Date.now();  	let offset = userTimestamp - serverTimestamp;    	// Get a unix timestamp for the server date and add the offset  	let adjustedTimestamp = new Date(dateStr).getTime() + offset;    	// Return a date object adjusted for the user's timezone  	return new Date(adjustedTimestamp);    }  

And you would use it like this…

let dateFromAPI = '2025-01-31T11:50:15';  let apiTimezone = 'America/Denver';    let userTime = getDateInCurrentUsersTimezone(dateFromAPI, apiTimezone);  

Here's a working demo.

You can find a copy of this in my membership toolkit as well.

This seems hard!

Yea, it is!

Working with times and dates in JavaScript is a lot more annoying than it should be. There's a new Temporal API in the works that will make this a lot easier, but it's nowhere near ready for use in production yet.

Like this? A Go Make Things membership is the best way to support my work and help me create more free content.

Cheers,
Chris

Want to share this with others or read it later? View it in a browser.

Share :

Facebook Twitter Google+
0 Komentar untuk "[Go Make Things] Getting a date in the current user's timezone with JavaScript"

Back To Top