JS HTML Time value.getHours() is showing NaN - javascript

I am learning JS and as part of this I was trying to build a HTML page where based on date and time input of EST, I will get IST date and hour in the label. However, I am struggling to get hours and minutes out from HTML input so that I can set these hours into selected. If any of you experts can help me out here, will be really appreciated.
<HTML>
<HEAD>
<script language="JavaScript">
function calcTime() {
var output = document.getElementById("result");
var selectedDate = document.getElementById('date').value;
var selectedTime = document.getElementById('time');
selectedDate.setHours(selectedTime.getHours());
selectedDate.setMinutes(selectedTime.getMinutes());
var traceHours = new Time(selectedTime);
var markHours = traceHours.getHours();
nd = new Date(selectedTime + (3600000 * 9.5));
output.innerHTML = updatedDate;
}
</script>
</HEAD>
<BODY>
Select a date:
<input id=date type="date">
<input id=time type="time">
</br>
<button id=submit onclick="calcTime();return false;">Click to check Time</button>
Time to EST is:
<B>
<blink>
<DIV style="background-color: rgb(25, 236, 208)" id=result></DIV>
</blink>
</B>
</BODY>
</HTML>

You have to get the .value of the input elements, which are text, create a new Date from their values and then you can call a Date method on that.
You also have several other HTML and JavaScript problems, for example, there is no such thing as a Time object in JavaScript, so this will fail:
var traceHours = new Time(selectedTime);
Frankly, it's clear that you've gotten this code straight out of 1995 (seriously). There are a lot of things that are no longer correct (i.e. blink has been deprecated for many years [thank God!]).
See the HTML and JavaScript comments below for details.
<HTML>
<HEAD>
<style>
/* Don't do styling in HTML, separate it into CSS */
#result { font-weight:bold; background-color: rgb(25, 236, 208); }
</style>
</HEAD>
<BODY>
Select a date:
<input id=date type="date">
<input id=time type="time"><br> <!-- There's no such thing as </br> -->
<button id="submit">Click to check Time</button>
<!-- Don't use inline event attributes like onClick. Do that work in JavaScript.
Also, don't use an HTML tag because of the formatting the browser applies to
it, like <b>. Styling is done with CSS, not HTML. -->
Time to EST is: <DIV id="result"></DIV>
<!-- Place your <script> element just before the closing BODY tag
so that by the time the parser gets here, all the HTML will have
been read into memory. Also, type=javascript isn't necessary since
that is the default type. -->
<script>
// Get your DOM references just once, not every time the function runs
var output = document.getElementById("result");
var dateElement = document.getElementById('date')
var timeElement = document.getElementById('time');
// Set up events in JavaScript, not with inline HTML event attributes
document.getElementById("submit").addEventListener("click", calcTime);
function calcTime() {
// Create a new Date object from the two HTML inputs
var est = new Date(dateElement.value + " " + timeElement.value);
// Write out the results. Don't use .innerHTML when there is no HTML.
// Use .textContent instead and just call .toISOString() to get UTC time.
result.textContent = 'USA time: '+ est.toISOString();
}
</script>
</BODY>
</HTML>

There's a couple things going on here:
You need to call value after document.getElementById('time'), otherwise you're working with the element
Both selectedDate and selectedTime are just string values, so you won't be able to call DateTime methods like getHours on either of them
To address the above, simply create a new instance of Date using selectedDate and selectedTime like this: var date = new Date(selectedDate + ': ' + selectedTime); This works because the Date constructor can accept any parseable date string (cf, this should be ok for your purposes, but be aware that this won't work on all browsers, so be careful)
You can now display the stringified date on your page
Full code example:
var output = document.getElementById('result');
var selectedDate = document.getElementById('date').value;
var selectedTime = document.getElementById('time').value;
var date = new Date(selectedDate + ': ' + selectedTime);
output.innerHTML = date;
A couple extra things, you'll probably want to add quotes around your id= tags in the HTML; the </br> should be <br /> or just <b>; probably want to stick with lowercase for all your HTML tags; the <blink> tag is considered obsolete and has been deprecated, so you shouldn't use it; setting innerHTML on an element will completely replace the child nodes, so your string "Time to EST is:" will be entirely replaced by the string value for your date object.
Hope this all helps.

Look at answer from #jcjcjcjc.
Furthermore if you really want to access hours and minutes or set the time you can do
var selectedTime = document.getElementById('time').value;
hours = selectedTime.split(":")[0];
minutes = selectedTime.split(":")[1];
document.getElementById('time').value = "13:45:00.000";

you can use getHours() on object Date only
function calcTime() {
var date = document.getElementById("date").value,
time = document.getElementById("time").value;
var dateTime = date +" " + time;
nd = new Date(dateTime);
}

This is a great community, I really appreciate all of you taking time to resolve my problem. Scott Marcus, jcjcjc, 45ccccw32, Leung King Tim and everyone. I was able to resolve my issue by the code provided by Scott. Please find below the final code for anyone looking for this in future.
var output = document.getElementById("result");
var dateElement = document.getElementById('date')
var timeElement = document.getElementById('time');
document.getElementById("submit").addEventListener("click", calcTime);
function calcTime() {
// Create a new Date object from the two HTML inputs
var est = new Date(dateElement.value + " " + (timeElement.value));
if(est.getMinutes>=30){
est.setMinutes(est.getMinutes() + 30);
est.setHours(est.getHours + 1);
}
else{
est.setMinutes(est.getMinutes() + 30);
}
if(est.getHours>=24){
est.setHours(est.getHours() + 9);
est.setDate(est.getDate() + 1);
}
else{
est.setHours(est.getHours() + 9);
}
result.textContent = 'India time: '+ est.toLocaleString();
}
#result { font-weight:bold; background-color: rgb(25, 236, 208); }
<HTML>
<HEAD>
</HEAD>
<BODY>
Select a date:
<input id=date type="date">
<input id=time type="time"><br>
<button id="submit">Click to check Time</button>
Time to EST is: <DIV id="result"></DIV>
</BODY>
</HTML>

Related

Auto Insert Tag in Blogger

I am trying to use jquery to automatically insert "Latest Post" tag to every post published "today."
Here's the code I put in my blogger right before </head>:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
<![CDATA[
var today = new Date();
var date = today.getMonth() + "/" + today.getDate() + "/" + today.getFullYear();
var x = document.getElementsByTagName("abbr").innerHTML;
var NewIn = "\",\"Latest Post"
if (date === x){
$(span.post-labels).append(NewIn);
}
]]>
</script>
I did some search and tried my best to put together the codes. However, it doesn't work and I don't know which steps are wrong. Hope someone can help me out as I am not very good at coding.
Thanks in advance.
#aax Thanks for the help, I'm still trying, but just doesn't work.
The main ideas on how to make this work:
Use $(document).ready(function() { ... } to manipulate the page. If not used, the page might not have been loaded and the manipulation fails.
Date.getMonth is zero-based (e.g. the month of January is represented by 0 and July is 6. When comparing with the blog post date, you need to add 1 to it.
You need to decide for each blog post if it should have the "latest" tag. So you need some kind of loop which checks the date for each blog post and then adds the tag for this post only. In jQuery, use $(<parent element>).find("<sub element selector>") to select a child element of a specific parent.
I tested the following code on your blog:
$(document).ready(function() {
var today = new Date();
var date = (today.getMonth() + 1) + "/" + today.getDate() + "/" + today.getFullYear();
var newIn = $.parseHTML(', Latest Post')
$("div.post").each(function() {
if ($(this).find("a.timestamp-link abbr").text() === date) {
$(this).find("span.post-labels").append(newIn);
}
});
});
According to https://www.w3schools.com/tags/tag_script.asp the script tag should generally look like this:
<script type="text/javascript">
//<![CDATA[
...
//]]>
</script>

My javascript application I created only works once and then can't be replicated unless I delete the file

I hope I'm not asking a "duhish" question with what I'm asking but I do need some clarification on what's going on in the "background". I created a simple clock exercise for myself this weekend. It works, it shows up on my browser and shows the current time just like I want it to. That said, when I try to create it again with a different HTML file and Javascript file.... it doesn't work again. It shows up in the original file I created but on the same file that has the same code... It doesn't show the timer.
Here's the HTML I wrote down in the original
<html>
<head>
<title>Kenneth's clock</title>
<meta charset="UTF-8">
<link rel='stylesheet' type='text/css' href=''>
<script src='clock.js'></script>
</head>
<body>
<p id ='clock'></p>
</body>
</html>
Then the Javascript.
function getTime() {
var now = new Date();
var h = now.getHours();
var m = now.getMinutes();
var s = now.getSeconds();
m = checkTime(m);
s = checkTime(s);
document.getElementById('clock').innerHTML = h + ":" + m + ":" + s;
setTimeout('getTime()', 1000);
function checkTime(time) {
if(time<10) {
time = "0" + time;
}
return time;
}
}
window.onload = function() {
getTime();
}
Imagine if I recreated that entire thing again and I changed the id on the new HTML file to digitalclock. I make the new code in javascript to getElementById('digitalclock') and viola.. new exercise to learn basic javascript....
For some reason, it doesn't work. What's going on in the backend to make it so that I can't get it to work?

use JavaScript to make a webpage that forwards to a URL which includes the date?

I wanted to make a bookmark that uses today's date in the URL; in other words, when the bookmark is launched, the end of the URL would vary each day. So today's would end in .../2017/1/31 and tomorrow's would end in .../2017/2/1.
I thought it might be easiest to just make a barebones HTML page that includes an inline JavaScript to get current year, month, and date and append it to the main URL (which never changes). Does this make sense? Is there an easier way to accomplish this?
I'm okay with HTML elements, but kind of clueless about JavaScript; I literally copied a snippet from another stackoverflow answer that sounded decent and put it into my head tags as you can see below, and tried to adapt my URL into the ahref link:
<HTML>
<head>
<script>var d=new Date();</script>
</head>
<body>
<a href="http://wol.org?t="+d.getTime()>Continue</a>
</body>
</HTML>
The following will run without need for clicking any buttons:
<HTML>
<head>
<script>
Date.prototype.yyyymmdd = function() { //returns YYYY/MM/DD
var mm = this.getMonth() + 1; // getMonth() is zero-based
var dd = this.getDate();
return [this.getFullYear(),
(mm>9 ? '' : '0') + mm,
(dd>9 ? '' : '0') + dd
].join('/');
};
var date = new Date();
window.location.href = "your.url.com/" + date.yyyymmdd();
</script>
</head>
<body>
</body>
</HTML>
Date function from this answer: https://stackoverflow.com/a/3067896/3803371
Note I usually don't condone modification of native prototypes, but I'm feeling lazy today.
You cannot use javascript expression outside script tag. So you cannot call d.getTime like this. Instead of you can do this:
<a id="c" href="">Continue</a>
<script>
(function() { // wait for window load
var d=new Date();
var a = document.getElementById("c");
a.href = "http://wol.org?t="+d.getTime();
})();
</script>
There's a couple problems with your code. First, you're mixing HTML and JavaScript. JavaScript can only go between the <script> tags. Also, the script needs to go below your link you want to modify.
If you want to get the date in the form year/month/day you'll have to do some modification to the date string you get back from your Date object. What I do below is basically get the date string and split it by / into an array. I know the first index is the month, second is the day, and third gives me the year. I store each of those into a variable to use and rearrange later.
I then had to locate the <a> element using getElementById() and then I changed the href value using my date variables.
var dateString = new Date().toLocaleDateString();
var dateArray = dateString.split('/');
var month = dateArray[0];
var day = dateArray[1];
var year = dateArray[2];
var dateOrder = year + "/" + month + "/" + day;
console.log(dateOrder);
var a = document.getElementById('link');
a.href += dateOrder;
<a id="link" href="http://wol.org?t=">Continue</a>
<script>
// Javascript from above goes here
</script>

How to write to page in javascript using date method

I want to display a quote depending on what day it is. Example: Quote of the day is Tuesday March 10 : "Quote here". I have the alert displaying the date, day and time but I want it to display on the page in the h2 header. So after it loads the alert I want the quote, depending on which day it is, to be written on the page.
Thank you.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Class 6 array assignment starter file</title>
<script>
var venomArray = new Array();
venomArray[0] = " Ability is nothing without opportunity - Napoleon Bonaparte";
venomArray[1] = " Nothing happens unless first we dream - Carl Sandburg";
venomArray[2] = "quote3";
var today = new Date();
//var text = document.getElementById('expression').firstChild.nodeValue = venomArray[i];
// if I uncomment this, It displays the index 1 for tuesday. How do I get it to write to the page? Would I use firstChildnodeValue?
alert("The quote of the day for: "+today+ venomArray[today.getDay()-1]);
</script>
</head>
<body>
<section>
<h2 style = "color:red" id='expression'> Quote of the Day : </h2>
<h3> All of the Quotes are listed below:</h3>
<p>
Nothing happens unless first we dream - Carl Sandburg<br>
Believe you can and you're halfway there - Theodore Roosevelt<br>
A place for everything, everything in its place - Benjamin Franklin<br>
Don't let the fear of striking out hold you back - Babe Ruth<br>
We can't help everyone, but everyone can help someone - Ronald Reagan<br>
With self-discipline most anything is possible - Theodore Roosevelt
</p>
</section>
</body>
</html>
You need to set the innerHTML property of the element
document.getElementById("expression").innerHTML = ' Quote of the Day : ' +
today+venomArray[today.getDay()-1];
Check this.. This may help your question
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Class 6 array assignment starter file</title>
</head>
<body>
<section>
<h2 style = "color:red" id='expression'> Quote of the Day : <span id="quote"></span> </h2>
<h3> All of the Quotes are listed below:</h3>
<p>
Nothing happens unless first we dream - Carl Sandburg<br>
Believe you can and you're halfway there - Theodore Roosevelt<br>
A place for everything, everything in its place - Benjamin Franklin<br>
Don't let the fear of striking out hold you back - Babe Ruth<br>
We can't help everyone, but everyone can help someone - Ronald Reagan<br>
With self-discipline most anything is possible - Theodore Roosevelt
</p>
</section>
<script type="text/javascript">
var venomArray = new Array();
venomArray[0] = " Ability is nothing without opportunity - Napoleon Bonaparte";
venomArray[1] = " Nothing happens unless first we dream - Carl Sandburg";
venomArray[2] = "quote2";
venomArray[3] = "quote3";
venomArray[4] = "quote4";
var t = new Date();
//alert(t.getDay());
//var text = document.getElementById('expression').firstChild.nodeValue = venomArray[i];
// if I uncomment this, It displays the index 1 for tuesday. How do I get it to write to the page? Would I use firstChildnodeValue?
// alert("The quote of the day for: "+today+ venomArray[today.getDay()-1]);
document.getElementById("quote").innerHTML = venomArray[t.getDay()-1];
</script>
</body>
</html>
You can use innerHtml property of an element to update the content, something like:
document.getElementById('expression').innerHTML = "Quote";
This is an implementation in pure JavaScript. You usually use some kind of templating now a days to display variable text in a web page.
Use This :-
<script>
var venomArray = new Array();
venomArray[0] = " Ability is nothing without opportunity - Napoleon Bonaparte";
venomArray[1] = " Nothing happens unless first we dream - Carl Sandburg";
venomArray[2] = "quote3";
var today = new Date();
//var text = document.getElementById('expression').firstChild.nodeValue = venomArray[i];
// if I uncomment this, It displays the index 1 for tuesday. How do I get it to write to the page? Would I use firstChildnodeValue?
//alert("The quote of the day for: "+today+ venomArray[today.getDay()-1]);
/*Add this Code*/
var display_date = "today"+ venomArray[today.getDay()-1];
$('h2').html(display_date );
</script>

Parse time data from HTML using jQuery

I've got a javascript widget on my page that outputs times for Sunrise and Sunset. The following code is what gets output (assume that these times change every day). I have no control over the output from the widget.
<div id="sun_container">
<div class="details">
Sunrise: <strong>7:00AM</strong> |
Sunset: <strong>4:30PM</strong>
</div>
</div>
Elsewhere on my page I have an image tag that looks like this:
<div id="sun_button">
<img src="images/day.png">
</div>
I want to parse out the sunrise time and the sunset time and compare these against the current server time (which I can output via PHP if necessary).
If the current server time is not between the sunrise and sunset times, then I want to change the image src to "images/night.png".
Any ideas on how I could do this?
EDIT: I'm now outputting the server time in the page <head> using:
var server_time = "<?=date("H:i:s", time())?>";
which outputs something like this:
var server_time = "17:07:41";
You can do it very easily with the DateJS JavaScript library:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
<script type="text/javascript" src="http://www.datejs.com/build/date.js"></script>
<script type="text/javascript">
$(document).ready(function(){
var sunrise = Date.parse($(".details strong:eq(0)").text());
var sunset = Date.parse($(".details strong:eq(1)").text());
if(Date.parse("" + server_time).between(sunrise, sunset)) {
$("img").attr("src","images/day.png")
}
else {
$("img").attr("src","images/night.png")
}
});
</script>
Try it here!
I think you're looking for this post: What is the best way to parse a time into a Date object from user input in Javascript?
Same premise, it's javascript, but this seems to be the best solution.
EDIT
Also, see #Ender's solution on how to retrieve the data.
Well, you can get the sunrise/sunset times by doing something like the following:
var sunrise = $('#sun_container .details strong:eq(0)').text();
var sunset = $('#sun_container .details strong:eq(1)').text();
From there probably write the server time into a JS var, do your comparison, and then:
if (isNight) {
$('#sun_button img').attr('src', 'images/night.png');
}
That should get you started.
Assuming you can generate a container like this with 24 hour time:
<div id="server_time">18:00</div>
<script>
$(function() {
// Assume server_time is 24hr
var server = new Date(Date.parse("2000-01-01 " + $('#server_time').text()));
var sunrise = $('#sun_container .details strong:eq(0)').first().text();
var sunset = $('#sun_container .details strong:eq(1)').last().text();
// strip off AM/PM
sunrise = sunrise.substring(0, sunrise.length-2);
sunset = sunset.substring(0, sunset.length-2);
// Parse to standard dates
sunrise = new Date(Date.parse("2000-01-01 " + sunrise)) ;
sunset = new Date(Date.parse("2000-01-01 " + sunset));
// Add tweleve hours to compensate for PM
sunset.setHours(sunset.getHours() + 12);
if (server < sunrise || server > sunset)
$('#sun_button > img').attr('src', 'images/night');
});
</script>

Categories

Resources