How to set am/pm in javascript - javascript

I am using new Date() to create a customize time, and also I'm using a function to format time in am/pm:
const formatTimeAMPM = (date, midnight = { am: "AM", pm: "PM" }) => {
var hours = date.getHours();
var minutes = date.getMinutes();
var ampm = hours >= 12 ? ` ${midnight.am}` : ` ${midnight.pm}`;
hours = hours % 12;
hours = hours ? hours : 12; // the hour '0' should be '12'
minutes = minutes < 10 ? "0" + minutes : minutes;
hours = hours < 10 ? "0" + hours : hours;
var strTime = hours + ":" + minutes + " " + ampm;
return strTime;
};
let startDate = new Date(Date.now());
console.log('before change :',formatTimeAMPM(startDate));
startDate.setHours(8, 30, 0, 0);
console.log('after change :',formatTimeAMPM(startDate));
If you run the snippet, you will see console logs the 8:30 pm , Can anyone tell me how to set am for it when I change hour the startDate ?

Your am/pm check is backwards:
var ampm = hours >= 12 ? ` ${midnight.am}` : ` ${midnight.pm}`;
If the hour is >= 12, it should be PM not AM, so it should be:
var ampm = hours >= 12 ? ` ${midnight.pm}` : ` ${midnight.am}`;
Now if you run it, it will show 8:30 AM and if you set the hour to 20 it will show 8:30 PM
This will fix your current issue but it would be better to use an existing library for date formatting since it can get complicated, especially with i18n. There a couple popular ones such as date-fns and moment.js that will do the heavy lifting for you.

Related

Vue JS time-slots-generator how to get value from object then display PM / AM

I use the time-slots-generator package, to display the time from 0:15 to 24:00, the problem is that this package does not provide the ability to display AM / PM and I will have to do it manually
To do this, I took some example code from StackOverflow, then changed it a little, and got the following result
let hours = 23;
let minutes = 32;
let ampm = hours >= 12 ? 'pm' : 'am';
hours = hours % 12;
hours = hours ? hours : 12; // the hour '0' should be '12'
minutes = minutes < 10 ? '0'+minutes : minutes;
const strTime = hours + ':' + minutes + ' ' + ampm;
console.log(strTime)
If you, for example, change the value of the hours to 17 and change the variable minute to 25, then you get 17:25 pm I think the logic of this function is clear to you, it checks the value and displays either AM or PM
Now I need to link this logic with my time generator, at the moment I am using a loop to display the time from 0:15 to 24:00 as I mentioned earlier, this loop looks like this
data() {
return {
timeSlots: (ts.getTimeSlots([], true, "quarter")),
}
},
formatAMPM() {
let val = Object.values(this.timeSlots);
for (let prop in val) {
console.log( val[prop]);
}
}
With this loop, I get the following result
As you already understood, now I need to do so that the times are displayed either AM or PM, maybe you can offer a simpler solution to solve this problem I will be glad about every advice, you can see this example in codesandbox
You could move that time formatting snippet into a function that could be called on each timeSlots value:
export default {
methods: {
formatAMPM() {
const formatTime = time => {
const parts = time.split(':');
let hours = Number(parts[0]);
let minutes = Number(parts[1]);
let ampm = hours >= 12 ? 'pm' : 'am';
hours = hours % 12;
hours = hours ? hours : 12; // the hour '0' should be '12'
minutes = minutes < 10 ? '0' + minutes : minutes;
const strTime = hours + ':' + minutes + ' ' + ampm;
return strTime;
};
Object.entries(this.timeSlots).forEach(([key, time]) => {
this.timeSlots[key] = formatTime(time);
});
},
}
}
demo
For dates, I recommend a more robust and flexible solution. Using date-fns' format.
You can find an example here: https://github.com/date-fns/date-fns/issues/946#issuecomment-452766765
But using something like format(new Date(), "hh:mmaaaaa'm'") should be good enough, and flexible on top of it. Also, unlike Momentjs, this lib is optimized and does the job well.

jquery timepicker time start issue

I have and timepicker in my code. code is given below.
function getCurrentTime(date) {
var hours = date.getHours(),
minutes = date.getMinutes(),
ampm = hours >= 12 ? 'pm' : 'am';
hours = hours % 12;
hours = hours ? hours : 12; // the hour '0' should be '12'
minutes = minutes < 10 ? '0'+minutes : minutes;
return hours + ':' + minutes + ' ' + ampm;
}
var cur_time = new Date();
cur_time.setHours(cur_time.getHours() + 1);
$('.pickup_time').timepicker({
timeFormat: 'hh:mm p',
interval: 30,
minTime: getCurrentTime(new Date()),
// minTime: '1',
// maxTime: '11:30pm',
// startTime: '01:00',
dynamic: false,
dropdown: true,
scrollbar: true
});
$('.pickup_time').timepicker('setTime', cur_time);
Using this code i am getting dropdown like which is given below in image .what i exactly want is i want to start the time from the 2:00 when its 1:43. and if time is 1:25 i want it toi start from 01:30.
Help needed on this can any one have idea about this ???
In order to round the current time to the next half hour, adjust your getCurrentTime() function as follows:
function getCurrentTime(date) {
// extract hours and minutes from given date
var hours = date.getHours(),
minutes = date.getMinutes();
// round minutes to half hour or next hour
if (minutes <= 30) {
minutes = "30";
} else {
minutes = "00";
hours = (hours + 1) % 24; // loop on 24 hours
}
// calc if morning or afternoon
var ampm = hours >= 12 ? "pm" : "am";
// adjust hour to 12h format
hours = hours % 12;
hours = hours ? hours : 12; // the hour '0' should be '12'
return hours + ":" + minutes + " " + ampm;
}

Date formating gives different results in Chrome than in other browsers?

I want to show the time in a readable format. So I am using the below js code. But the output is different in Chrome and IE. How do I change the code to give the same output across all the browsers ?
The output in IE : 12:46 am
In Chrome : 6:16 am
Time zone is : UTC +05:30
var unReadableDate = "2016-01-25T00:46:00";
var newDate = new Date(unReadableDate);
//var timeZoneOffset = (new Date()).getTimezoneOffset();
//newDate.setMinutes(newDate.getMinutes() - timeZoneOffset);
alert(formatAMPM(newDate));
//below function formats time in am and pm
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;
}
Can you please try replacing this
var unReadableDate = "2012-06-25T00:46:00.000Z"
var newDate = new Date(unReadableDate);
//var timeZoneOffset = (new Date()).getTimezoneOffset();
//newDate.setMinutes(newDate.getMinutes() - timeZoneOffset);
alert(formatAMPM(newDate));
//below function formats time in am and pm
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;
}
Converting a UTC format string to a date using Javascript Date constructor is not reliable. If you want to tackle timezone issues with date you should use moment.js. To understand more you can use below link.
Javascript Date issue
OR simple way to resolve the issue is pass individual arguments in the date instead of complete string. To understand more you can use below link
DateTime UTC
Your problem is that your date string being treated as a local time vs it being treated as UTC.
Just make it unambiguous by specifying the time zone. Change
var unReadableDate = "2016-01-25T00:46:00";
to
var unReadableDate = "2016-01-25T00:46:00Z";

How to get the time converted to desired time zone

I have the following code
INPUT:
var dateString = "10/30/2014 02:15 PM +00:00";
var a = dateString .split(/[^0-9]/);
var dateVal=new Date(a[0],a[1]-1,a[2],a[3],a[4],a[5]);
var minutes=dateVal.setMinutes(dateVal.getMinutes() + 330);
var hours = dateVal.getHours();
if(parseInt(hours,10) < 10){
hours = "0"+hours;
}
var minutes = parseInt(dateVal.getMinutes());
var ampm = parseInt(hours, 10) >= 12 ? 'PM' : 'AM';
hours = parseInt(hours % 12);
hours = hours ? hours : 12; // the hour '0' should be '12'
minutes = minutes < 10 ? '0'+minutes : minutes;
strTime = hours + ':' + minutes + ' ' + ampm;
return strTime
OUTPUT:
Actual: 7:45 AM
Expected : 7:45 PM
I am able to get the time zone converted but not able to get the desired output as i like to get 7:45 PM but i always get the way opposite.
Can some help me out with this.
The problem is, that a time past midday doesn't get detected, when you convert the string. Try to search for PM and if found increase your hours by twelve:
var dateString = "10/30/2014 02:15 PM +00:00";
var a = dateString .split(/[^0-9]/);
if(dateString.indexOf("PM") != -1) a[3] = Number(a[3]) + 12;
var dateVal=new Date(a[0],a[1]-1,a[2],a[3],a[4],a[5]);

display time am/pm inside a div with javascript

Hi Everyone I am sorry if this question has been answered before but I haven't been able to find a solution. I am completely new to js so please be nice :)
I wanted to ask how can I have the time display inside a div? I can't get this function to display on my page. When I launch the page in the browser, it is just blank.
Thank you, I hope my question makes sense.
document.getElementById("para1").innerHTML = formatAMPM(date);
function formatAMPM(date) {
var elem = document.getElementById("para1");
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;
}
You need this:
document.getElementById("para1").innerHTML = formatAMPM(new Date());
And you might also want to wrap it in something like jQuery's ready() to make sure the DOM has been loaded:
$(document).ready(function() {
// Handler for .ready() called.
});
http://api.jquery.com/ready/
jQuery's isn't the only way, but just a suggestion.
document.getElementById("para1").innerHTML = formatAMPM();
function formatAMPM() {
var date = new Date();
var hours = date.getHours();
var minutes = date.getMinutes();
var ampm = hours >= 12 ? 'pm' : 'am';
hours = hours % 12;
hours = hours || 12;
minutes = minutes < 10 ? '0'+minutes : minutes;
var strTime = hours + ':' + minutes + ' ' + ampm;
return strTime;
}
DEMO VIEW
You can return it in a user-familiar time string with toLocaleTimeString().
A replace will remove the seconds counter-
function formatAMPM() {
var d=new Date().toLocaleTimeString();
return d.replace(/^(\d{2}:\d{2}):\d{2}(.*)/, '$1$2');
}
Or you can call this or your method on a timer-
onload= function(){
window.showTimer= setInterval(function(){
var date= new Date(),
hours= date.getHours(),
time= date.getMinutes();
if(time<10) time= '0'+time;
document.getElementById("para1").innerHTML=
(hours%12 || 12)+':'+time+(hours>= 12? ' pm':' am');
},1000);
}

Categories

Resources