I am attempting to build a simple time counter
I tried it in the browser:
All works fine, but console.log(todaysDate.split(" "));
this genartes error:
custom.js:2 Uncaught TypeError: todaysDate.split is not a function
I am not using the split function correctly? Or because of its structure(Sun Feb 06 2022 00:11:51 GMT+0530 (India Standard Time)
), it is not splitting properly:
todaysDate
is an object, not a string.
1 Like
How to convert this to a string?
If I use this: console.log(JSON.stringify(todaysDate));
it gives: “2022-02-05T19:42:33.856Z”
which is not what I was looking for.
Have you tried todaysDate.toLocaleDateString()
?
What format do you want?
1 Like
Archibald:
What format do you want?
I got stuck with string conversion so I wanted to visualize
Sun Feb 06 2022 01:38:35 GMT+0530 (India Standard Time)
to this →
['Sun', 'Feb', '06', '2022', '01:38:35', 'GMT+0530', '(India Standard Time)']
Try:
todaysDate.toString().split(" ")
1 Like
Thank you. Please guide me as I want to give a try to achieve this.
Today’s date can be fetched by: new Date();
Some future dates: Mach-31-2022, for example
I want to calculate the time difference between the two and then append in an HTMl that ill have counter: Days Minutes Hours Seconds.
How should I try this? what functions should In access?
You can subtract one date object from another which will give a time diffence in milliseconds. So here is how to get the number of whole days:
const todaysDate = new Date();
const endDate = new Date(2022, 2, 31)
const difference = endDate - todaysDate;
const days = Math.floor(difference/1000/60/60/24)
Note March is month number 2 because months start from zero. Don’t ask me why
2 Likes
I know, they are set to the base value of "0"
not "1"
. thanks for all your support, you are very supportive and helpful.
I was able to make this, and it is working:
Probably, there is a more elegant way to do this, and JS veterans may help me further.
1 Like
That looks good.
There is an issue with the blue shapes changing shape when there’s only one digit.
You may like to consider whether using the ‘remainder’ operator would simplify things:
For what it’s worth, some simplification is possible if you divide by 1000 just once:
const timeInSecs = (futureDate - todaysDate)/1000;
2 Likes
Thanks, I will try to incorporate them and create a new codepen.
The remainder can be used only once, then math.floor will chuck out the remainder, and in further mathematical operation, the remainder is not going to work.
There’s no need for .getTime()
.
Here’s another way of doing it:
Note constant ‘days’ is not an integer.
If you use CodePen to format the JavaScript you get a lot of extra brackets . . . . . which I think should not be needed.
1 Like
Excellent, You have sanitized this. So neat Now.
system
Closed
May 8, 2022, 10:07pm
16
This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.