Kodeclik Logo

Our Programs

Learn More

Schedule

Kodeclik Blog

Find your current time zone in Javascript

We will learn how to find your current time zone in your Javascript program. To understand how to do this, we will write and embed our Javascript code inside a HTML page like so:

<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>Find your current time zone in Javascript</title>
</head>

<body>
  <script>
  </script>
</body>

</html>

In the above HTML page you see the basic elements of the page like the head element containing the title (“Find your current time zone in Javascript”) and a body with an empty script tag. Any HTML markup goes inside the body tags and any Javascript code goes inside the script tags.

Finding your timezone

How to get timezone in Javascript

First, we will use the “new Date()” constructor to obtain a Date object containing the current date and time. Here is a simple Javascript program that initializes a Date object and then writes it out into your HTML page:

<script>
  const today = new Date()
  document.write(today)
  document.write("<BR>")
</script>

The output will be (depending on the day you read this blogpost and/or run this program):

Tue Jul 19 2022 07:13:35 GMT-0400 (Eastern Daylight Time)

Note that the Date object contains the time as well as the date. To find the timezone, once your Date object is created, use the getTimezoneOffset() method:

<script>
  const today = new Date()
  document.write(today.getTimezoneOffset())
  document.write("<BR>")
</script>

The output is:

240

What does 240 mean? 240 is the difference between Coordinated Universal Time (UTC) and local time in minutes. In other words, this is 240/60 = 4 hours behind UTC (because the output is positive). In other words, EDT is 4 hours behind UTC.

(Note that this will not always be the case because the United States adjusts clocks for daylight savings.)

If the returned value is positive, this means that the given time zone is behind UTC. If the returned value is negative, this means that the given time zone is ahead of UTC.

Try running this program in your time zone and see what values you obtain and write to us about it!

If you liked this blogpost, checkout our blogpost on computing yesterday’s and tomorrow’s dates in Javascript!

Want to learn Javascript with us? Sign up for 1:1 or small group classes.

Kodeclik sidebar newsletter

Join our mailing list

Subscribe to get updates about our classes, camps, coupons, and more.

About

Kodeclik is an online coding academy for kids and teens to learn real world programming. Kids are introduced to coding in a fun and exciting way and are challeged to higher levels with engaging, high quality content.

Copyright @ Kodeclik 2024. All rights reserved.