Using split pop and join all at once can it work? - javascript

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?

You 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(":"));

Related

Javascript indexOf in date array always resulting -1

I'm facing a problem checking whether a date is in my array or not.
I refer to this article How to correctly use JavaScript indexOf in a date array
But when I use it in my project, it always results in -1.
Here's my code
for (var current = dateStart; current <= dateEnd; current.setDate(current.getDate() + 1)) {
console.log(this.leaveState.currentHoliday.map(Number).indexOf(+current));
}
I need to check whether current date is in currentHoliday array or not.
I think mapping doesn't require to loop into your array.
and -1 is somehow mean that the date does not exist in your array.
Maybe because in every loop you add a day to it before you see the actual day.
I think you could try:
var alldays = [...];
//you should eliminate these two codes
// datestart = something;
// dateend = something;
var holiday;
for(var i in alldays){
console.log(alldays.map(Number).indexOf(this.leaveState.currentHoliday));
}

How do I convert a string with no delimiters into a date?

I want to convert 20170603 into a date. I want to use the function new Date(2017,06,03), but how do I extract the numbers from the date? I tried using
new Date(parseInt(startDate.substr(0,4)), parseInt(startDate.substr(5,6)) -1, parseInt(startDate.substr(6,8)))
However, this gives me very weird values. How do I extract the exact numbers into the Date function?
Second parameter of substr function is length of string you want to extract;
new Date(parseInt(startDate.substr(0,4)),
parseInt(startDate.substr(4,2)) - 1,
parseInt(startDate.substr(6,2)));
substr Method (String) (JavaScript)
Using replace() with RegExp
const date_str = "20170603";
console.log( new Date( date_str.replace( /(\d{4})(\d{2})(\d{2})/, "$1/$2/$3" ) ) );
If using an external library is not an issue. I would suggest using moment.js
There are many methods available. For your case.
var d = new moment("20170603 ", "YYYYMMDD").toDate();
I am using this lib to solve a lot of challenges.
Slicing by character counts:
new Date(my_str.match(/(....)(..)(..)/).slice(1,4).join('/'))

(javascript) Calling a method on an object inside an array

I am not sure i named the title properly. Let me explain my little problem.
My code snipppet is pretty short:
var myArray= new Array([new Date()],[123],[abc]);
var time = myArray[0].getTime()
I want the time saved in the object inside the array to be written to the "time" variable.
I just thought this would work but i get an error.
Uncaught TypeError: myArray[0].getTime is not a function
Apparently i am doing it wrong, but i have no idea what is the problem and how to do it right.
Its inside of another array:
var time = myArray[0][0].getTime();
// ^^^
Working example:
var myArray = new Array([new Date()], [123], ['abc']),
time = myArray[0][0].getTime();
alert(time);
You define array of arrays [[], [], []], so to get date element you should do this:
var myArray= new Array([new Date()],[123],['abc']);
var time = myArray[0][0].getTime();
The code you used creates an array with arrays inside:
var myArray= new Array([new Date()],[123],[abc]); // [[new Date()],[123],[abc]]
So you would have to call
myArray[0][0].getTime()
You probably wanted to do
var myArray = new Array(new Date(),123,abc); // [new Date(),123,abc]
Or simply
var myArray = [new Date(),123,abc];
As a tip, when you get these errors, try console.loging the variables. You would see the date you expected was actually an array with a single position, and would easily found out the error :)

How do I separate the date from the string

This is a string 2011-11-09 00:00:00
So now how do I separate the date i.e. 2011-11-09 from the string, I dont want to use the slicing here if anyone has better options or ideas please let me know..
var date = '2011-11-09 00:00:00'.split(' ')[0];
You can split it by ' ' and then the first element will contain what you want.
console.log('2011-11-09 00:00:00'.split(' ')[0]);
Like this:
var date = 'This is a string 2011-11-09 00:00:00'.match(/\d{4}-\d{2}-\d{2}/)
if you dont want to use splicing, like you posted you could create a Date obj
var newDate = new Date(2011-11-09 00:00:00);
then to get the date, just use the toString override
var dateOnly = newDate.toString("YYYY-mm-dd");
That is if you dont want to use splicing or splits

manipulating date object with javascript

i have been tinkering with the date object.
I want to add a dynamic amount of days to a day and then get the resulting date as a variable and post it to a form.
var startDate = $('#StartDate').datepicker("getDate");
var change = $('#numnights').val();
alert(change);
var endDate = new Date(startDate.getFullYear(), startDate.getMonth(),startDate.getDate() + change);
does everything correctly except the last part. it doesnt add the days onto the day
take this scenario:
startdate = 2011-03-01
change = 1
alert change = 1
endDate = 2011-03-11 *it should be 2011-03-02*
thank you to all the quick replies.
converting change variable to an integer did the trick. thank you.
parseInt(change)
just to extend on this: is there a way to assign a variable a type, such as var charge(int)?
You may have fallen victim to string concatenation.
Try changing your last parameter in the Date constructor to: startDate.getDate() + parseInt(change)
See this example for future reference.
convert change to a number before adding it. it looks like you're getting a string concatenation operation rather than the addition you're expectingin your code.
I believe you are concatenating instead of using the mathematical operator. Try this instead,
var endDate = new Date(startDate.getFullYear(), startDate.getMonth(),startDate.getDate() + (+change));
It looks like you are not adding the ending day, you are concatinating it so '1' + '1' = '11'
use parseInt() to make sure you are working with integers
example
var change = parseInt($('selector').val());
Also, with this solution, you could easily end up with a day out of range if you are say on a start date of the 29th of the month and get a change of 5

Categories