24 hours format hrs and min with leading zeros - javascript

Looking for 24 hours format, hours + min string
for ex :
2:05 AM => 0205 ( need to add leading zero)
4:30 PM => 1030
hours & min should be 4 digit always, thanks for your help.

created below logic..
var d = new Date();
var sHours = d.getHours();
var sMinutes = d.getMinutes();
if (sHours < 10) sHours = "0" + sHours;
if (sMinutes < 10) sMinutes = "0" + sMinutes;
var seq_no = sHours + "" + sMinutes;

Related

How to set Am and Pm for Clock [duplicate]

I have buttons with the names of big cities.
Clicking them, I want to get local time in them.
$('#btnToronto').click(function () {
var hours = new Date().getHours();
var hours = hours-2; //this is the distance from my local time
alert ('Toronto time: ' + hours + ' h'); //this works correctly
});
But how can I get AM or PM ?
You should just be able to check if hours is greater than 12.
var ampm = (hours >= 12) ? "PM" : "AM";
But have you considered the case where the hour is less than 2 before you subtract 2? You'd end up with a negative number for your hour.
Try below code:
$('#btnToronto').click(function () {
var hours = new Date().getHours();
var hours = (hours+24-2)%24;
var mid='am';
if(hours==0){ //At 00 hours we need to show 12 am
hours=12;
}
else if(hours>12)
{
hours=hours%12;
mid='pm';
}
alert ('Toronto time: ' + hours + mid);
});
You can use like this,
var dt = new Date();
var h = dt.getHours(), m = dt.getMinutes();
var _time = (h > 12) ? (h-12 + ':' + m +' PM') : (h + ':' + m +' AM');
Hopes this will be better with minutes too.
const now = new Date()
.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit', hour12: true })
.toLowerCase();
Basically you just need to put {hour12: true} and it's done.
result => now = "21:00 pm";
If hours is less than 12, it's the a.m..
var hours = new Date().getHours(), // this is local hours, may want getUTCHours()
am;
// adjust for timezone
hours = (hours + 24 - 2) % 24;
// get am/pm
am = hours < 12 ? 'a.m.' : 'p.m.';
// convert to 12-hour style
hours = (hours % 12) || 12;
Now, for me as you didn't use getUTCHours, it is currently 2 hours after
hours + ' ' + am; // "6 p.m."
very interesting post. in a function that take a date in parameter it can appear like that :
function hourwithAMPM(dateInput) {
var d = new Date(dateInput);
var ampm = (d.getHours() >= 12) ? "PM" : "AM";
var hours = (d.getHours() >= 12) ? d.getHours()-12 : d.getHours();
return hours+' : '+d.getMinutes()+' '+ampm;
}
with date.js
<script type="text/javascript" src="http://www.datejs.com/build/date.js"></script>
you can write like this
new Date().toString("hh:mm tt")
cheet sheet is here format specifiers
tt is for AM/PM
Try this:
h = h > 12 ? h-12 +'PM' : h +'AM';
The best way without extensions and complex coding:
date.toLocaleString([], { hour12: true});
How do you display javascript datetime in 12 hour AM/PM format?
here is get time i use in my code
let current = new Date();
let cDate = current.getDate() + '-' + (current.getMonth() + 1) + '-' + current.getFullYear();
let hours = current.getHours();
let am_pm = (hours >= 12) ? "PM" : "AM";
if(hours >= 12){
hours -=12;
}
let cTime = hours + ":" + current.getMinutes() + ":" + current.getSeconds() +" "+ am_pm;
let dateTime = cDate + ' ' + cTime;
console.log(dateTime); // 1-3-2021 2:28:14 PM
var now = new Date();
var hours = now.getHours();
var minutes = now.getMinutes();
var ampm = hours >= 12 ? 'pm' : 'am';
hours = hours % 12;
hours = hours ? hours : 12;
minutes = minutes < 10 ? '0' + minutes : minutes;
var timewithampm = hours + ':' + minutes + ' ' + ampm;
return timewithampm;
var dt = new Date();
var h = dt.getHours(),
m = dt.getMinutes();
var time;
if (h == 12) {
time = h + ":" + m + " PM";
} else {
time = h > 12 ? h - 12 + ":" + m + " PM" : h + ":" + m + " AM";
}
//var time = h > 12 ? h - 12 + ":" + m + " PM" : h + ":" + m + " AM";
console.log(`CURRENT TIME IS ${time}`);
This will work for everytime,
function Timer() {
var dt = new Date()
if (dt.getHours() >= 12){
ampm = "PM";
} else {
ampm = "AM";
}
if (dt.getHours() < 10) {
hour = "0" + dt.getHours();
} else {
hour = dt.getHours();
}
if (dt.getMinutes() < 10) {
minute = "0" + dt.getMinutes();
} else {
minute = dt.getMinutes();
}
if (dt.getSeconds() < 10) {
second = "0" + dt.getSeconds();
} else {
second = dt.getSeconds();
}
if (dt.getHours() > 12) {
hour = dt.getHours() - 12;
} else {
hour = dt.getHours();
}
if (hour < 10) {
hour = "0" + hour;
} else {
hour = hour;
}
document.getElementById('time').innerHTML = hour + ":" + minute + ":" + second + " " + ampm;
setTimeout("Timer()", 1000);
}
Timer()
<div id="time"></div>

Get HTML5 datetime-local exact value

Try to use this, http://jsfiddle.net/mdg2u4ut and you will notice the hour will be different with what you've set, like in my case
I think it's because of the timezone problem.
I can just hardcoded -8 for the hour variable in my case but that's not the smart way of doing it.
<input type="datetime-local" onblur="formatDate(this.value)" />
<p id="para"></p>
my JS
function formatDate(date) {
if(date){
date = new Date(date);
var hours = date.getHours();
var minutes = date.getMinutes();
var format = hours < 12 ? 'AM' : 'PM';
hours = hours % 12;
hours = hours ? hours : 12; // making 0 a 12
minutes = minutes < 10 ? '0'+minutes : minutes;
var time = hours + ':' + minutes + ' ' + format;
var output = date.getMonth()+1 + "/" + date.getDate() + "/" + date.getFullYear() + " " + time;
document.querySelector('#para').innerHTML = output;
}
}
Use getUTC methods instead. jsFiddle
var hours = date.getUTCHours();
var minutes = date.getUTCMinutes();
var format = hours < 12 ? 'AM' : 'PM';
hours = hours % 12;
hours = hours ? hours : 12; // making 0 a 12
minutes = minutes < 10 ? '0'+minutes : minutes;
var time = hours + ':' + minutes + ' ' + format;
var output = date.getUTCMonth()+1 + "/" + date.getUTCDate() + "/" + date.getUTCFullYear() + " " + time;

convert time 12 hour format to 24 hour format and vice-versa

I want a js script that converts inputted time to 24 hour format or 12 hour format.
Example,
time is entered as 10_10_am result should be:-
10:10 AM (12 hr format) and 10:10 (24 hr format)
time is entered as 10_10_pm result should be:-
10:10 PM (12 hr format) and 22:10 (24 hr format)
HTML
<input type="text" id="textbox1"/>
<input type="button" id="b1" value="convert 12 hr"/>
<input type="button" id="b2" value="convert 24 hr"/>
<div id="result"></div>
JS
$(document).ready(function () {
function am_pm_to_hours(time) {
console.log(time);
var hours = Number(time.match(/^(\d+)/)[1]);
var minutes = Number(time.match(/:(\d+)/)[1]);
var AMPM = time.match(/\s(.*)$/)[1];
if (AMPM == "pm" && hours < 12) hours = hours + 12;
if (AMPM == "am" && hours == 12) hours = hours - 12;
var sHours = hours.toString();
var sMinutes = minutes.toString();
if (hours < 10) sHours = "0" + sHours;
if (minutes < 10) sMinutes = "0" + sMinutes;
return (sHours +':'+sMinutes);
}
function hours_am_pm(time) {
var hours = time[0] + time[1];
var min = time[2] + time[3];
if (hours < 12) {
return hours + ':' + min + ' AM';
} else {
hours=hours - 12;
hours=(hours.length < 10) ? '0'+hours:hours;
return hours+ ':' + min + ' PM';
}
}
$('#b1').click(function(){
var n = $('#textbox1').val();
var n1 =n.split('_');
var time = hours_am_pm(n1[0]+n1[1]);
$('#result').text(time);
});
$('#b2').click(function(){
var n = $('#textbox1').val();
var n1 =n.split('_');
var time = am_pm_to_hours(n1[0]+':'+n1[1]+' '+n1[2]);
$('#result').text(time);
});
});
Working Demo http://jsfiddle.net/cse_tushar/xEuUR/
updated after Adrian P 's comment
Working Demo http://jsfiddle.net/cse_tushar/xEuUR/4
function hours_am_pm(time) {
var hours = Number(time.match(/^(\d+)/)[1]);
var min = Number(time.match(/:(\d+)/)[1]);
if (min < 10) min = "0" + min;
if (hours < 12) {
return hours + ':' + min + ' AM';
} else {
hours=hours - 12;
hours=(hours < 10) ? '0'+hours:hours;
return hours+ ':' + min + ' PM';
}
}
I am not sure if there is any specific function that already exists, but this is fairly easy to write.
Considering your input is always ##_##_pm or ##_##_am you can split this string on every _ and grab first value as hours, second as minutes and compare the third
and
if it's pm add 12 hours to the hours variable for 24 hr format.
You need a function that takes 2 parameters (format and string)
It will look something like this:
function timeFormat(format, str){
var timeParts=str.split("_");
if(format==12){
return timeParts[0] + ":" + timeParts[1] + " " + timeParts[2];
}else if(format == 24){
var hours = timeParts[0];
if(timeParts[2] == "pm")
hours += 12;
return hours + ":" + timeParts[1]
}
}

Get the day name and time on posting automatically using JavaScript

This will result in a javascript format: 9 Aug, 2012
var month = [1,2,3,4,5,6,7,8,9,10,11,12];
var month2 = ["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];
var day = postdate.split(-)[2].substring(0,2);
var m = postdate.split(-)[1];
var y = postdate.split(-)[0];
for(var u2=0;u2<month.length;u2++){
if(parseInt(m)==month[u2]) {
m = month2[u2] ; break;
}
}
var daystr = day+ ' ' + m + ', ' + y ;
How to add the day name and time in javascript above?
Ex: Thursday, 9 Aug, 2012 5:28 PM
getDay(); will return the dayname
getTime() will return the time in milliscond since 1970.
You can get the day name using gatDay();
and here is a function to display time.
function displayTime() {
var currentTime = new Date();
var currentHours = currentTime.getHours();
var currentMinutes = currentTime.getMinutes();
var currentSeconds = currentTime.getSeconds();
// Pad the minutes and seconds with leading zeros, if required
currentMinutes = (currentMinutes < 10 ? "0" : "" ) + currentMinutes;
currentSeconds = (currentSeconds < 10 ? "0" : "" ) + currentSeconds;
// Choose either "AM" or "PM" as appropriate
var timeOfDay = (currentHours < 12 ) ? "AM" : "PM";
// Convert the hours component to 12-hour format if needed
currentHours = (currentHours > 12 ) ? currentHours - 12 : currentHours;
// Convert an hours component of "0" to "12"
currentHours = (currentHours == 0 ) ? 12 : currentHours;
// Compose the string for display
var currentTimeString = currentHours + ":" + currentMinutes + " " +currentSeconds+" "+ timeOfDay;
$("#clock").html(currentTimeString);
}

Javascript: How to turn the time (stored as a fraction) into a readable string?

I have the time stored as a fraction (done so it can be displayed on a graph), e.g. 15.5 is 3.30pm and 23.25 is 11.15pm. I need to turn those numbers into strings in the format HH:MM:SS. Is there a simple way of doing this?
var fraction = 23.5;
var date = new Date(2000, 1, 1); // use any date as base reference
date.setUTCSeconds(fraction * 3600); // add number of seconds in fractional hours
Then use a date formatting script such as this, or Date.js if you're not fond or formatting and padding.
date.format("HH:MM:ss"); // 23:30:00
See an example. I'm using the formatting function from here.
Something like this ?
var fraction = 14.5;
var hours = Math.floor(fraction); // extract the hours (in 24 hour format)
var mins = 60 * (fraction - hours); // calculate the minutes
t = new Date(); // create a date/time object
t.setHours(hours); // set the hours
t.setMinutes(mins); // set the mins
console.log(t.toTimeString()); //show it
or completely manual
var fraction = 14.5;
var hours = Math.floor(fraction);
var mins = 60 * (fraction - hours);
var ampm = ((fraction % 24) < 12) ? 'am' : 'pm';
formatted = ('0' + hours % 12).substr(-2) + ':' + ('0' + mins).substr(-2) + ':00 ' + ampm;
console.log(formatted);
Update
And a version with seconds as well..
var fraction = 14.33;
var hours = Math.floor(fraction);
var allseconds = 3600 * (fraction - hours);
var minutes = Math.floor(allseconds / 60);
var seconds = Math.floor(allseconds % 60);
var ampm = ((fraction % 24) < 12) ? 'am' : 'pm';
formatted = ('0' + hours % 12).substr(-2) + ':' + ('0' + minutes).substr(-2) + ':' + ('0' + seconds).substr(-2) + ' ' + ampm;
console.log(formatted);
Manual function:
var time = function(num) {
if(num < 0 || num >= 24) {throw "Invalid number");}
var x = num > 13 ? num - 12 : num;
var h = Math.floor(x);
var min = x - h;
var ampm = num >= 12 && num < 24 ? "pm" : "am";
return (h + ":" + Math.floor(min * 60) + ampm);
};
Tests:
time(13.40); // 1:24pm
time(11.25); // 11:15pm
time(12.50); // 12:30pm
time(23.50); // 11:30pm
time(0.50); // 0:30am
time(24.00); // error!!

Categories

Resources