Convert ISO time to H:MM am|pm in JavaScript [duplicate] - javascript

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
JavaScript seconds to time with format hh:mm:ss
Seems to me that this is a simple task, but I have not yet managed to make this work.
Essentially, I am starting with a string that contains an ISO-formatted time (HH:MM:SS) and I am wondering how to convert it to H:MM am|pm using JavaScript.
Any help is much appreciated.

hello this may help you... its a jquery plugin called moments...
A lightweight (4.8k) javascript date library for parsing, manipulating, and formatting dates.
Moment.js

This simple function should do the trick:
function convertTime (isoTime) {
var hours = parseInt(isoTime.substring(0, 2), 10),
minutes = isoTime.substring(3, 5),
ampm = 'am';
if (hours == 12) {
ampm = 'pm';
} else if (hours == 0) {
hours = 12;
} else if (hours > 12) {
hours -= 12;
ampm = 'pm';
}
return hours + ':' + minutes + ' ' + ampm;
}
Should be self-explanatory. See this jsfiddle for example: http://jsfiddle.net/nscXP/3/

Just because there are solutions coming in that will fail to handle the noon hour or midnight hour properly, I'm going to toss my hat in the ring, even though it's not that different from what's been offered (aside than the fact it works properly):
var isoToCommonTime = function(iso) {
var groups = iso.match(/^(\d\d):(\d\d)/),
hour = +groups[1],
ampm = (hour >= 12) ? "pm" : "am";
if(hour > 12) {
hour -= 12;
} else if(hour === 0) {
hour = 12;
}
return hour + ":" + groups[2] + " " + ampm;
};

Something like this would work...
input = "12:34:45";
groups = input.match(/(.+):(.+):(.+)/);
if (groups[1] > 12) {
hour = groups[1] - 12;
unit = "pm";
} else {
hour = groups[1];
unit = "am";
}
minutes = groups[2];
Edit: There's some great points in the comments about issues with this at noon and midnight. I'll leave fixing these problems as an exercise to the reader. (I feel that the actual interesting part here is doing the string parsing)

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.

Converting specific military time with Angular and Javascript filter

I see that I various times like
01:45
//and
15:00
I assume that date is HH:MM in military ?
While have I seen some advanced functions then parse sentences and even some using the seconds like HH:MM:SS , I am wanting a simple and accurate way of getting the HH:MM
So I assume 15:00 is 3:00 ?
This function below is not going to work because I already have ":"
so below assumed HHMM right? when I believe I need HH:MM to be parsed ?
var getTravelTimeFormatted = function (str) {
var hours = Math.trunc(str / 60),
minutes = str % 60;
return hours + ':' + minutes;
};
Update
Ok, I assume that 15:00 is 3:00 , right?
So i stripped out the incoming ":" and then add it back
problem is the result is 25.0 so what does that mean?
var getTravelTimeFormatted = function (str) {
str = str.replace(/:/g,'');
var hours = Math.trunc(str / 60),
minutes = str % 60;
return hours + ':' + minutes;
};
console.log(getTravelTimeFormatted('15:00'));
Given a string HH:MM you can just split then subtract 12 hours. Here's a naive solution that doesn't check for invalid input.
function TwelveHourFormat(time) {
var dtParts = time.split(":");
var hours = dtParts[0];
var minutes = dtParts[1];
var suffix = "AM";
if (hours > 12) {
hours = hours - 12;
suffix = "PM";
}
else if (hours == "00") {
hours = 12;
suffix = "AM";
}
else if (hours == "12") {
suffix = "PM";
}
return (hours + ":" + minutes + " " + suffix);
}
This is a duplicate of Converting 24 hour time to 12 hour time w/ AM & PM using Javascript. Jasen's answer is fine, and more concise than the duplicate, but the function can be a little more concise:
/* Convert time in 24 hour hh:mm format to 12 hour h:mm ap format
** #param {string} time - in hh:mm format (e.g. 14:30)
** #returns {string} time in 12 hour format (e.g. 2:30 PM)
*/
function to12HourTime(time) {
var b = time.split(/\D/);
return (b[0]%12 || 12) + ':' + b[1] +
(b[0]<11? ' AM' : ' PM');
}
// Some tests
['23:15','2:15','03:15','00:30'].forEach(function(v) {
console.log(v + ' => ' + to12HourTime(v));
});

JavaScript isolate and format hours and minutes as 4-digit number [duplicate]

This question already has answers here:
Javascript, Time and Date: Getting the current minute, hour, day, week, month, year of a given millisecond time
(4 answers)
Closed 6 years ago.
I'm working on a project where I need to get the hours and minutes alone without the semicolon (:) separating them, and represent them in a variable, myTime, as a 4-digit number. Here is my code:
var now = new Date();
var time = now.toString().substr(16,5)
Use the .getHours() and .getMinutes() methods of Date objects to get these numbers. To get a 4-digit number representation (as a zero-padded string), concatenate and zero-pad as necessary with ('0000' + (hours * 100 + minutes)).slice(-4)as demonstrated below:
var now = new Date();
var hours = now.getHours();
var minutes = now.getMinutes();
var myTime = ('0000' + (hours * 100 + minutes)).slice(-4);
//note that myTime is a zero-padded string of length 4
console.log(now.toString(), hours, minutes, myTime);
To get Hours or Minutes from a datetime use the associated functions myDate.getHours() or myDate.getMinutes()
Edit: you probably don't want military time so adding 12 hour conversion...
var mt = getHoursMinutesSeconds(new Date());
alert(mt);
function getHoursMinutesSeconds(date) {
var h = date.getHours();
h = ((h + 11) % 12 + 1);
var m = date.getMinutes();
var myTime = addZero(h) + addZero(m);
return myTime;
}
function addZero(i) {
if (i < 10) {
i = "0" + i;
}
return i;
}

Live Digital clock with timezones

I have a digital clock that is running and it works great but I want to have multiple clocks running with different timezones. I am on the west coast and I would like the time to be different when people look at it in different timezones. How can I accomplish this?
function displayTime() {
var currentTime = new Date();
var hours = currentTime.getHours();
var minutes = currentTime.getMinutes();
var seconds = currentTime.getSeconds();
var meridiem = "AM";
if (hours > 12) {
hours = hours - 12;
meridiem = "PM";
}
if (hours === 0) {
hours = 12;
}
if(hours < 10) {
hours = "0" + hours;
}
if(minutes < 10) {
minutes = "0" + minutes;
}
if(seconds < 10) {
seconds = "0" + seconds;
}
var clockDiv = document.getElementById('clock');
clockDiv.innerText = hours + ":" + minutes + ":" + seconds + " " + meridiem;
}
displayTime();
setInterval(displayTime, 1000);
});
To get the time in any timezone based on the current system time (which might be wrong, but that may not really matter), create a Date and just adjust the UTC time values by the required offset, then use UTC methods to build your formatted string.
e.g.
/* Return a time string in h:m:s a/p format
**
** #param {number} offsetInMinutes - offset of required timezone in minutes
** #returns {string} formatted time string
*/
function getTimeInZone(offsetInMinutes) {
function z(n) {return (n<10?'0':'') + n;}
var d = new Date();
d.setUTCMinutes(d.getUTCMinutes() + offsetInMinutes);
var h = d.getUTCHours();
return z(h%12||12) + ':' + z(d.getUTCMinutes()) + ':' +
z(d.getUTCSeconds()) + ' ' + (h<12? 'am' : 'pm');
}
// Time at UTC-08:00
document.write(getTimeInZone(-480));
You say you're "on the west coast", but not of where, so I'll assume USA where the likely timezone offset is UTC-08:00 (-480 minutes). So to always show the time in that timezone (with the usual caveat that the system clock may not be correct), you'd do:
getTimeInZone(-480);
Also note that innerText is a IE proprietary property and not supported in all browsers.

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";

Categories

Resources