You are right that slicing and dicing the string representation of a date is not the right way. Parsing a local time string without a specific locale is even worse, and asking for trouble.
A Date
object in JavaScript has getHours()
and getMinutes()
methods.
The result will be in 24-hour format. If you need, you can convert that to am-pm format based on the hour. The resulting code will be more efficient and more predictable than parsing the string representation.
For example:
var timestamp = new Date();
var hours = timestamp.getHours();
var ampm;
if (hours < 12) {
ampm = 'AM';
} else {
ampm = 'PM';
if (hours > 12) {
hours -= 12;
}
}
For the record, this code to get the time part in rawTime
is very poor:
var timeArray = time.split(":");
var spaceDeliTime = timeArray.join(" ");
var rawTime = spaceDeliTime.split(" ");
var extrTime = rawTime.splice(2,1);
For one thing, the sequence of split by colons -> join by spaces -> split by spaces is really silly. Probably you could have achieved the same thing by simply taking a substring.
The most disturbing part is the splice
at the end: the result is stored in extrTime
but never used. On closer look it turns out the main purpose of that splice
was its side effect of mutating the rawTime
array. The logic would have been much more clear if you used array indexes to get the segments that you want rather than slicing and dicing an array.
If parsing the string representation, this would have been a simpler, more efficient, less confusing solution:
function makeTime () {
var timesStamp = new Date();
var time = timesStamp.toLocaleTimeString();
var timePart = time.substr(0, time.indexOf(":", 2))
var spaceAndAmPmPart = time.substr(time.lastIndexOf(' '))
return timePart + spaceAndAmPmPart;
}
But I still recommend the different approach using getHours
and getMinutes
.