Zohrabin Clean
Zohrabin Clean

Reputation: 9

How to get AM/PM work correctly with time in Javascript

I've this Javascript code for displaying time(according to time zone) and date but the issue is with AM/PM. It's not automatically updating as time changes; after many tries I failed in auto-updating, hence looking for some help here. Below is the code:

$(document).ready(function(){
// Create two variable with the names of the months and days in an array
// Count 3 variable for months
var monthNames = [ "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" ]; 
var dayNames= ["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"]

// Create a newDate() object
var newDate = new Date();
// Extract the current date from Date object
newDate.setDate(newDate.getUTCDate());
// Output the day, date, month and year   
$('#Date').html(/*dayNames[newDate.getUTCDay()] + " " + */monthNames[newDate.getMonth()] + ' ' + newDate.getDate() + ', ' + newDate.getFullYear());

setInterval( function() {
  // Create a newDate() object and extract the seconds of the current time on the visitor's
  var seconds = new Date().getUTCSeconds();
  // Add a leading zero to seconds value
  $("#sec").html(( seconds < 10 ? "0" : "" ) + seconds);
  },1000);

setInterval( function() {
  // Create a newDate() object and extract the minutes of the current time on the visitor's
  var minutes = new Date().getUTCMinutes();
  // Add a leading zero to the minutes value
  $("#min").html(( minutes < 10 ? "0" : "" ) + minutes);
  },1000);

setInterval( function() {
  // Create a newDate() object and extract the hours of the current time on the visitor's
  var hours = new Date().getUTCHours();
    var ampm    = 'AM';
if(hours > 5)
{
    hours -= 5; // Time Zone
    ampm = 'AM'; // AM/PM According to Time Chosen
}
    else if(hours == 5)
{
    ampm = 'PM';    
};

  // Add a leading zero to the hours value
  $("#hours").html(( hours < 10 ? "0" : "" ) + hours);

  $("#ampm").html(ampm);
  }, 1000); 
});

<span id="hours"></span>:<span id="min"></span>&nbsp;<span id="ampm"></span>&nbsp;&nbsp;<span id="Date"></span>

Upvotes: 0

Views: 7410

Answers (3)

bal simpson
bal simpson

Reputation: 196

Here's something simpler:

const getFormattedDate = (date) => {
  return date.toLocaleString('en-GB', { day: 'numeric', month: 'short', year: 'numeric', hour: 'numeric', minute: 'numeric', hour12: true })
}

Upvotes: 1

RobG
RobG

Reputation: 147413

I'm not really sure what you're trying to do, but if you are trying to use the host system to set a timezone of UTC-0500 then display the date and time in a particular format, there are many questions here about that already.

A simple method is to get a host date, shift the time based on the host timezone offset and compensate for your default 5 hours. Then format the time appropriately. The time is adjusted in minutes as that's what getTimezoneOffset returns and suits cases where the offset isn't even hours.

Once you've adjusted the date, setting am/pm is as simple as:

var ampm = d.getHours() < 12? 'am' : 'pm';

Call the function as often as required to show the current time.

// Return a date adjusted to UTC-0500
function getOffsetDate() {
  var d = new Date();
  // Set to UTC-0500: add timzone offset then subtract 300 mins
  d.setMinutes(d.getMinutes() + d.getTimezoneOffset() - 300);
  return d;
}

// Format time as hh:mm:ss ap 
function formatTime(d) {
  function z(n){return (n<10? '0' : '') + n}
  var ap = d.getHours() < 12? 'am' : 'pm';
  return z(d.getHours()) + ':' + z(d.getMinutes()) + ':' +
         z(d.getSeconds()) + ' ' + ap;
}

function showTime() {
  // Delay to just after next full second
  var delay = 1020 - new Date().getMilliseconds();
  // Show time
  document.getElementById('time').textContent = formatTime(getOffsetDate());
  // Call again
  setTimeout(showTime, delay);
}

showTime();
<div>The time in timezone UTC-0500 is <span id="time"></span></div>

Upvotes: 3

Hamuel
Hamuel

Reputation: 633

Maybe some library will make your life is easier

https://momentjs.com/timezone/

I would not want to write this myself but it is definitely good practice this is exactly what you want I think and keep calling the time in setInterval to update the time.

Upvotes: 0

Related Questions