I really love Javascript and I wrote my code like this. I feel like it should work. Am I doing it in the wrong order? If it won't work like this why not?
var mydate = new Date();
alert( mydate.toLocaleTimeString().split(":").pop().join(':'));
split()
makes it an array, pop()
takes off the end of the array, join()
makes it a string again right?
I really love Javascript and I wrote my code like this. I feel like it should work. Am I doing it in the wrong order? If it won't work like this why not?
var mydate = new Date();
alert( mydate.toLocaleTimeString().split(":").pop().join(':'));
split()
makes it an array, pop()
takes off the end of the array, join()
makes it a string again right?
5 Answers
Reset to default 10You could use Array#slice
with a negative end/second argument.
Array#pop
returns the last element, but not the array itself. slice
returns a copy of the array with all emements from start without the last element.
var mydate = new Date();
console.log(mydate.toLocaleTimeString().split(":").slice(0, -1).join(':'));
No, pop()
will remove the last element from the array and return it.
To achieve what you're trying, you'll need to first assign the result of split()
to a variable you can then reference:
var mydate = new Date(),
myarr = mydate.toLocaleTimeString().split(':');
myarr.pop();
console.log(myarr.join(':'));
if all you want to achieve is hours:minutes, you can just simply do this
var mydate = new Date();
console.log(mydate.getHours() + ':' + mydate.getMinutes());
You are trying to use method chaining where next method in the chain uses the output of the previously executed method. Reason it's not working is because "join()" method is a prototype of an array but "pop()" returns an array element which doesn't aforementioned method that's why the error. refactor your code as below:
var myDate = new Date(),
myDateArr = myDate.toLocaleTimeString().split(':');
myDateArr.pop(); // Remove the seconds
myDate = myDateArr.join(':'); // Returns string
console.log(myDate);
Hope this helps.
Try this
var mydate = new Date();
alert( mydate.toLocaleTimeString().split(":").slice(0, 2).join(":"));