changing gethours in javascript to 1-12 - javascript

i'm trying to use the gethours() method in javascript but it keeps returning military time. can someone please help me out fixing it so that it displays clock time? (1-12). Thank you so much!
// Reroute from the conf.js script
var chat = $( '.chat-output' ),
message = function ( message, userId ) {
var dt = new Date(),
time = dt.getHours() + ":" + dt.getMinutes(); // + ":" + dt.getSeconds();
return $( '<div class="chat-message color-' + users[userId] + '">' +
'<div class="chat-id color-' + users[userId] + '"></div>' +
'<div class="chat-user-message">' + message + '</div>' +
'<div class="chat-time">' + time + '</div>' +
'</div>' );
},
addText = function ( text ) {
// log.innerHTML += text;
// log.scrollTop = log.scrollHeight;
console.log( text );
},
addRemoteText = function ( userId, text ) {
// addText( '[' + userId + ']: ' + text+'<br>' );
chat.append( message( text, userId ) );
chat.scrollTop( chat.get( 0 ).scrollHeight );
};

function ampm(date){
var dt= date || new Date,
h= dt.getHours(),
m= dt.getMinutes(),
s= dt.getSeconds(),
ampm;
if(h>12){
h-= 12;
ampm= (h%12)? ' PM': ' AM';
}
else ampm= (h%12)? ' AM': ' PM';
m= m<10? '0'+m: m;
s= s<10? '0'+s: s;
return [h, m, s].join(':')+ampm;
}
ampm()
/* returned value: (String)
11:52:55 PM
*/

Something like this?
var dt = new Date();
var hours = dt.getHours();
var ampm = hours > 11 ? 'PM' : 'AM';
if (hours > 12) {
hours -= 12;
} else if (hours === 0) {
hours = 12;
}
var time = hours + ":" + dt.getMinutes() + ' ' + ampm;
Fiddle

Here's another version of formatting a time in 12 hour format:
// Returns formatted time for given Date object, or
// current system time if d is falsey.
function getTime(d) {
d = d || new Date();
var hrs = d.getHours();
var pad = function(n){return (n<10?'0':'')+ +n};
return pad(hrs%12 || 12) + ':' + pad(d.getMinutes()) + ' ' + (hrs<12? 'AM':'PM');
}
console.log(getTime(new Date(2014,2,24, 0, 5))); // 12:05 AM
console.log(getTime(new Date(2014,2,24,10,25))); // 10:25 AM
console.log(getTime(new Date(2014,2,24,20,15))); // 08:15 PM
Note that 24hr time is preferred in many cases to avoid anomalies like 12:00 AM (which is really neither AM or PM) and 12:00 AM being before 01:00 AM.

Related

How do I reverse the countdown? | X Days, X Hours Passed

This is a countdown. How do I reverse this?
Eg.
X days X hours X seconds passed (after).
For example, how do I calculate the time that has passed since the day I was born in this code blog?
I am using this code blog ready. It counts down to the date the website will open. On the contrary, I want to calculate the elapsed time.
var clock = $('#clock');
if (clock.length) {
if (clock.hasClass('js-timer-elapsed')) {
// Elasped timer/countdown
//Put your date
var year = '2012';
var month = '07';
var day = '12';
var time = '00:00:00';
//End Put your date
var date = year + '/' + month + '/' + day + ' ' + time;
var now = new Date();
var dateFormat = 'YYYY/MM/DD hh:mm:ss';
var momentDate = moment(date, dateFormat);
var momentNow = moment(now, dateFormat);
var outputYears = moment(momentNow, dateFormat).diff(momentDate, 'years');
var outputYearsLabel = outputYears > 1 ? 'Years' : 'Year';
var dateCurrentYear = now.getFullYear() + '/' + month + '/' + day + ' ' + time;
var outputDays = moment(dateCurrentYear, dateFormat).diff(momentNow, 'days');
var outputDaysLabel = outputDays > 1 ? 'Days' : 'Day';
var outputMonths = moment(dateCurrentYear, dateFormat).diff(momentNow, 'months');
clock.countdown(date, {
elapse: true,
strftime: dateFormat
}).on('update.countdown', function(event) {
var output = [
'<div class="counter-container">',
'<div class="counter-box first"><div class="number">' + Math.abs(outputYears) + '</div><span>' + outputYearsLabel + '</span></div>', // Years
'<div class="counter-box first"><div class="number">' + Math.abs(outputMonths) + '</div><span>Months</span></div>', // Months
'<div class="counter-box first"><div class="number">' + Math.abs(outputDays) + '</div><span>' + outputDaysLabel + '</span></div>', // Days
'<div class="counter-box"><div class="number">%H</div><span>Hours</span></div>', // Hours
'<div class="counter-box"><div class="number">%M</div><span>Minutes</span></div>', // Minutes
'<div class="counter-box last"><div class="number">%S</div><span>Seconds</span></div></div>', // Seconds
'</div>'
].join('\n');
$(this).html(
event.strftime(output)
);
});
} else {
// Default countdown
clock.countdown('2022/10/14 12:00:00').on('update.countdown', function(event) {
var output = [
'<div class="counter-container"><div class="counter-box first"><div class="number">%-D</div><span>Day%!d</span></div>', //Days
'<div class="counter-box"><div class="number">%H</div><span>Hours</span></div>', //Hours
'<div class="counter-box"><div class="number">%M</div><span>Minutes</span></div>', //Minutes
'<div class="counter-box last"><div class="number">%S</div><span>Seconds</span></div></div>' //Seconds
].join('\n');
$(this).html(
event.strftime(output)
);
});
}
}

JS: Formatting time and date display on website

I have a script that prints the current date and time in JavaScript, but when it prints time, it's missing one 0. Here is the code:
var currentdate = new Date();
var datetime = "0" + currentdate.getDate() + ".0"
+ (currentdate.getMonth()+1) + "."
+ currentdate.getFullYear() + " "
+ currentdate.getHours() + ":"
+ currentdate.getMinutes();
document.write(datetime);
It should print 04.03.2016 15:04 and prints 04.03.2016 15:4.
Two digit minutes print fine.
Any leads?
Try this
var formatDateDigit = function (i) {
return i <= 9 ? ("0" + i) : i;
};
var currentdate = new Date();
var datetime = formatDateDigit(currentdate.getDate()) + "."
+ formatDateDigit(currentdate.getMonth()+1) + "."
+ currentdate.getFullYear() + " "
+ formatDateDigit(currentdate.getHours()) + ":"
+ formatDateDigit(currentdate.getMinutes());
document.getElementById('my_output_here').innerHTML = datetime;
<div id="my_output_here"></div>

Javascript if / else not working properly [Time Formatting AM/PM]

I am trying to have a div show the current time but it always shows it in military time, so I went to use an if / else statement to help but it doesn't seem to work.
Javascript
var time = new Date(Date.now());
var timeHour = time.getHours();
var timeHourFix = timeHour;
var timeMinute = time.getMinutes();
var formatted = timeHourFix + ":" + timeMinute;
if(time.getHours() > 12) {
timeHourFix = time.getHours() - 12 + "PM";
}else {
timeHourFix = time.getHours() + "AM";
};
$( document ).ready(function() {
$('#hourmin').text(formatted)
});
it should display the time like 5:35 PM but it still shows 17:35
That's because your are declaring the variable formatted before the timeHourFix is actually modified. Try the code below.
var time = new Date(Date.now());
var hour = time.getHours();
var t_hour = hour > 12 ? (hour - 12) : ((hour == 0) ? hour + 12 : hour);
var formatted = t_hour + " : " + time.getMinutes() + (hour > 11 ? " PM" : " AM");
$( document ).ready(function() {
$('#hourmin').text(formatted)
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p id=hourmin>
The time is not being formatted because the variable formatted is being set before timeHourFix or timeHour is being set. I think it's easiest to set formatted in the if else statement directly:
var time = new Date(Date.now());
var timeHour = time.getHours();
var timeMinute = time.getMinutes();
var formatted;
if(time.getHours() > 12) {
formatted = time.getHours() - 12 + ":" + timeMinute + " PM";
} else {
formatted = time.getHours() + ":" + timeMinute + " AM";
};
$( document ).ready(function() {
$('#hourmin').text(formatted)
});
In your case the problem was you were modifying the variable timeHourFix after it was appended to the string, there is no live linking between the string and the timeHourFix variable so any changes you make to the variable after the string concatenation will not be reflected in the original value.
Also there are multiple other issues like the AM/PM should be at the end of the string so that also have to be changed. Also there are other issues with timeHourFix like how the value 0030 will be handled, it should be shown as 12:30 AM not 00:30 AM
var time = new Date(Date.now());
var timeHour = time.getHours();
//set the hour part
var timeHourFix = timeHour > 12 ? timeHour - 12 : timeHour == 0 ? 12 : timeHour;
var timeMinute = time.getMinutes();
var formatted = timeHourFix + ":" + timeMinute;
//set the AM/PM at the end of the string
formatted += timeHour >= 12 ? ' PM' : ' AM';
$(document).ready(function() {
$('#hourmin').text(formatted)
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="hourmin"></div>
Because you set formatted before setting the right values to timeHourFix. Move the assignment of formatted to below the else block.
You could always do something like this if you want to simplify your code.
var time = new Date(Date.now());
var timeHour = time.getHours();
var timeHourFix = timeHour;
var timeMinute = time.getMinutes();
$(document).ready(function() {
var timeofday = "";
if(timeHour > 12) {
timeHourFix = timeHour - 12;
timeofday = "PM";
}else {
timeHourFix = timeHour;
timeofday = "AM";
};
var formatted = timeHourFix + ":" + timeMinute + " " + timeofday;
$('#hourmin').text(formatted)
});
This is perfectly working full code.
var time = new Date(Date.now());
var timeHour = time.getHours();
var timeHourFix = timeHour;
var timeMinute = time.getMinutes();
var formatted = timeHourFix + ":" + timeMinute;
if(time.getHours() > 12) {
time = time.getHours() - 12 + " : " + timeMinute + " PM";
}
else {
time = time.getHours() +" : " + timeMinute + " AM";
};
$( document ).ready(function() {
$('#hourmin').text(time)
});
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
</head>
<body>
<p id="hourmin">Time Display</p>
</body>
</html>

Script to show javascript time on server not working

I am trying to show a live javascript clock on my page which shows the time on the server. I found this snippet of code on the internet a few weeks back however it doesn't seem to be doing what it claimed to do. It is showing the client time, not the server time. Any idea why?
flag = true;
timer = '';
setInterval(function(){phpJavascriptClock(<?php echo time(); ?>);},1000);
function phpJavascriptClock(timestamp)
{
if ( flag ) {
timer = timestamp * 1000;
}
var d = new Date(timer);
var currentDate = d.getDate();
currentDate = currentDate < 10 ? '0'+currentDate : currentDate;
var hours = d.getHours();
var minutes = d.getMinutes();
var seconds = d.getSeconds();
var ampm = hours >= 12 ? 'PM' : 'AM';
hours = hours % 12;
hours = hours ? hours : 12; // the hour ’0' should be ’12'
minutes = minutes < 10 ? '0'+minutes : minutes;
seconds = seconds < 10 ? '0'+seconds : seconds;
var strTime = hours + ':' + minutes + ' ' + ampm;
var output = '';
output +=
'<a>'
+ '<i class="ace-icon fa fa-clock-o"></i>'
+ '<span class="">' + strTime + ' (SA)</span>'
+ '</a>'
;
document.getElementById("current_time").innerHTML = output ;
flag = false;
timer = timer + 1000;
}
I see these 4 constructors for a Javascript DATE:
new Date()
new Date(milliseconds)
new Date(dateString)
new Date(year, month, day, hours, minutes, seconds, milliseconds)
Could it be your timestamp is not milliseconds or dateString so Javascript just creates a new Date() object without any parameters (which is then the client time)?
Wrote a new jQuery based clock. Although it polls the server every minute, it works.
My controller that passes the time:
public function getServerTimeAction() {
global $config;
try{
$return["time"] = date("H:i a");
$return["timezone"] = $config->application->timezone;
$this->returnJson( JsonReturnObject::success( $return ) ) ;
} catch ( Exception $e ) {
$this->returnJson( JsonReturnObject::error( $e ) );
}
}
The jquery code:
function getServerTime() {
$.ajax({
url : "{{ url('json/session/get-server-time') }}",
cache : false,
success : function ( data ) {
if ( data.success ) {
var output = '';
output +=
'<a>'
+ '<i class="ace-icon fa fa-clock-o"></i>'
+ '<span class="">' + data.data.time + ' (SA)</span>'
+ '</a>'
;
$("#current_time").html(output);
setTimeout(getServerTime, 60000);
}
}
})
}

Uncaught ReferenceError: functionName is not defined

I have checked out this thread and this one but it didn't really help me.
I have a ASP:CheckBox control shown below.
<asp:CheckBox ID="chbArchived" runat="server" Checked='<%# Bind("archived") %>' OnClick=changeExpirationDate() />
My JavaScript are follows:
<script type="text/javascript">
$(document).ready(function () {
//alert("got here");
$('.insDateTime').datetimepicker({
ampm: true
});
changeExpirationDate(){
var currentDate = new Date;
var futureDateTime = (currentDate.getMonth() + 4) + '/' + currentDate.getDate() + '/' + currentDate.getFullYear() + ' ' + formatAMPM(currentDate);
var expiredDateTime = (currentDate.getMonth() + 1) + '/' + currentDate.getDate() + '/' + currentDate.getFullYear() + ' ' + formatAMPM(currentDate);
var archivedCheckbox = document.getElementById('cphContent_fmvNewsEventList_chbArchived').checked;
if(archivedCheckbox == true)
{
document.getElementById('cphContent_fmvNewsEventList_txtExpirationDate').value = expiredDateTime;
}
else{
document.getElementById('cphContent_fmvNewsEventList_txtExpirationDate').value = futureDateTime;
}
};
function formatAMPM(date) {
var hours = date.getHours();
var minutes = date.getMinutes();
var ampm = hours >= 12 ? 'pm' : 'am';
hours = hours % 12;
hours = hours ? hours : 12; // the hour '0' should be '12'
minutes = minutes < 10 ? '0'+minutes : minutes;
var strTime = hours + ':' + minutes + ' ' + ampm;
return strTime;
};
});
</script>
The problem is I kept getting this JavaScript error "Uncaught ReferenceError: changeExpirationDate is not defined" when I clicked on the checkbox. Any suggestion/help is much appreciated.
});
changeExpirationDate(){ <-- where is the function declaration?
var currentDate = new Date;
aka
function changeExpirationDate () {
Change
changeExpirationDate(){
to
function changeExpirationDate(){
The first makes it look like you are trying to call it; the second defines it.
Okay, after looking at one more time, I found out it was a very stupid mistake. I forgot the "function" before the function name, changeExpirationDate(), thus, it was giving me this error.

Categories