javascriptdatetimetimezonetimezone-offset

JS: displaying different timezones in specific format


Okay so I have a feature I'm working on for a new site where I need to display current time for both East Coast and West Coast. It needs to be display in the following way: NY 11:24:21 PM CA 08:24:21 PM

Thus far I've managed to get the time zones to start displaying but I need to make sure they both are pointing specifically only to EST & PST and that they are displaying inside the proper html blocks. I also need the AM/PM to wrap inside a html block.

Here is my sample code:

function showTime() {
    let date = new Date();
    let hours = date.getHours();
    let minutes = date.getMinutes();
    let seconds = date.getSeconds();
    let formatHours = convertFormat(hours)
    
    hours = checkTime(hours)
    hours = addZero(hours)
    minutes = addZero(minutes)
    seconds = addZero(seconds)
    let format = `NY ${hours}:${minutes}:${seconds} <small class="font-medium">${formatHours}</small>`
    let pstDate = date.toLocaleTimeString("en-US", {timeZone: "America/Los_Angeles"}, {timeStyle: 'short'})

    // Output Times
    $('.time-ny').html(format);
    $('.time-ca').html(pstDate);
}

function convertFormat(time) {
    let formmat = 'PM'
    if (time >= 12) {
        format = 'AM'
    }
    return formmat;
}

function checkTime(time) {
    if (time > 12) {
        time = time - 12;
    }
    if (time === 0) {
        time = 12;
    }
    return time
}

function addZero(time) {
    if (time < 10) {
        time = "0" + time;
    }
    return time
}
showTime()
setInterval(showTime, 1000)
body {
    min-height: 100vh;
    display: flex;
    align-items: center;
    justify-content: center;
    background-color: #000000;
    flex-direction: column;
}

.clock {
    font-family: sans-serif;
    font-size: 1rem;
    color: #fff;
}

.font-medium {
    font-weight: 500;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="clock time-ny"></div>
<div class="clock time-ca"></div>

Any help from you real JS coders would be super appreciated. I dabble in this stuff but it will never be my bread and butter.


Solution

  • Two adjustments are needed in your code to make it work correctly:

    1. Format the time string with the AM/PM wrapped in an HTML block.
    2. Get the East Coast and West Coast times by using the toLocaleString() method, and then pass it to a function which formats the time string(that mentioned above in point 1).

    A sample would look like:

    function showTime() {
      let date = new Date();
      let estDate = new Date(date.toLocaleString("en-US", {
        timeZone: "America/New_York"
      }));
      let pstDate = new Date(date.toLocaleString("en-US", {
        timeZone: "America/Los_Angeles"
      }));
    
      let formatNY = formatTime(estDate);
      let formatCA = formatTime(pstDate);
    
      // Output Times
      $('.time-ny').html(formatNY);
      $('.time-ca').html(formatCA);
    }
    // Created this method to format time.
    function formatTime(date) {
      let hours = date.getHours();
      let minutes = date.getMinutes();
      let seconds = date.getSeconds();
      let formatHours = convertFormat(hours);
    
      hours = checkTime(hours);
      hours = addZero(hours);
      minutes = addZero(minutes);
      seconds = addZero(seconds);
    
      return `${hours}:${minutes}:${seconds} <small class="font-medium">${formatHours}</small>`;
    }
    
    function convertFormat(time) {
      let format = 'AM';
      if (time >= 12) {
        format = 'PM';
      }
      return format;
    }
    
    function checkTime(time) {
      if (time >= 12) {
        time = time - 12;
      }
      if (time === 0) {
        time = 12;
      }
      return time;
    }
    
    function addZero(time) {
      if (time < 10) {
        time = "0" + time;
      }
      return time;
    }
    
    showTime();
    setInterval(showTime, 1000);
    body {
        min-height: 100vh;
        display: flex;
        align-items: center;
        justify-content: center;
        background-color: #000000;
        flex-direction: column;
    }
    
    .clock {
        font-family: sans-serif;
        font-size: 1rem;
        color: #fff;
    }
    
    .font-medium {
        font-weight: 500;
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <div class="clock time-ny"></div>
    <div class="clock time-ca"></div>


    Alternative solution:

    As a suggestion and alternative, you can also make your code concise by leveraging the Intl object which is now provided in the language itself. A sample code would look like below:

    function showTime() {
      const date = new Date();
      const estDate = new Date(date.toLocaleString("en-US", {
        timeZone: "America/New_York"
      }));
      const pstDate = new Date(date.toLocaleString("en-US", {
        timeZone: "America/Los_Angeles"
      }));
    
      const formatNY = formatTime(estDate, 'NY');
      const formatCA = formatTime(pstDate, 'CA');
    
      // Output Times
      $('.time-ny').html(formatNY);
      $('.time-ca').html(formatCA);
    }
    
    function formatTime(date, label) {
      const timeFormatter = new Intl.DateTimeFormat('en-US', {
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit',
        hour12: true,
      });
    
      const formattedTime = timeFormatter.format(date);
      const [time, period] = formattedTime.split(' ');
    
      return `${label} ${time} <small class="font-medium">${period}</small>`;
    }
    
    showTime();
    setInterval(showTime, 1000);
    body {
      min-height: 100vh;
      display: flex;
      align-items: center;
      justify-content: center;
      background-color: #000000;
      flex-direction: column;
    }
    
    .clock {
      font-family: sans-serif;
      font-size: 1rem;
      color: #fff;
    }
    
    .font-medium {
      font-weight: 500;
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <div class="clock time-ny"></div>
    <div class="clock time-ca"></div>