date - How to get AMPM work correctly with time in Javascript - Stack Overflow

I've this Javascript code for displaying time(according to time zone) and date but the issue is wi

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>

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>
Share Improve this question edited Jul 21, 2017 at 15:46 Ravi 31.4k44 gold badges124 silver badges180 bronze badges asked Jul 21, 2017 at 15:43 Zohrabin CleanZohrabin Clean 91 silver badge2 bronze badges 1
  • Note that newDate.setDate(newDate.getUTCDate()); may change the date, since the UTC date is not always the same as the local date. Why are you using UTC values then subtracting 5? Are you trying to set the date to a different time zone? There are plenty of questions about that already. – RobG Commented Jul 22, 2017 at 1:45
Add a ment  | 

3 Answers 3

Reset to default 3

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 pensate 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>

Here's something simpler:

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

Maybe some library will make your life is easier

https://momentjs./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.

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745176838a4615230.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信