I am using javaScript that detects the current year, and then wish to inset this into the HTML. I have the following but it seems to be undefined.
Here is my code...
HTML
<p>this year is <span id="year"></span></p>
JavaScript
var date = document.write(new Date().getFullYear());
document.getElementById("year").innerHTML = date;
I can do this in jQuery but I am trying to do this in vanailla javaScript, learning at the same time.
Thanks in advance.
Make sure your element is read and ready to be manipulated:
Also fix your JS:
<body>
<p>this year is <span id="year"></span></p>
<!-- JS before /body -->
<script>
document.getElementById("year").innerHTML = new Date().getFullYear();
</script>
</body>
Note that if my computer clock is off, I'll see the wrong Year.
If you use PHP it's simple as:
<p>this year is <span id="year"><?php echo date("Y"); ?></span></p>
in short:
<?= date("Y") ?>
Would it not be simpler and more efficient to simply do this in-line?
<p>this year is <script>document.write(new Date().getFullYear());</script>.</p>
<script>
window.onload = function(){
var date = new Date().getFullYear();
document.getElementById("year").innerHTML = date;
}
</script>
<p>this year is <span id="year"></span></p>
var date = (new Date()).getFullYear();
document.getElementById("year").innerHTML = date;
The problem is the document.write call. Try this:
var date = new Date().getFullYear();
document.getElementById("year").innerHTML = date;
This Javascript should work:
var date = (new Date().getFullYear()).toString();
document.getElementById("year").innerHTML = date;
to show date dynamically
<%=DateTime.Now.Year %>
<p>©2016 School Apps. All Rights Reserved.</p>
To show 2016 dynamically we use that code
Related
I'm having trouble updating the current year using js from an external file. The year in the html doesn't update to display the current year. Here's my html code;
<p>
Copyright © <span id="year">year</span>. All rights reseverved.
</p>
<script src="./js/shared.js"></script>
And here's my js code;
const year = document.querySelector('#year');
function date() {
year.innerHTML = new Date()
};
What am I doing wrong here, and what's the right way to achieve my goal?
Just try to add function invocation:
document.addEventListener('DOMContentLoaded', function(){
const year = document.querySelector('#year');
function date() {
year.innerHTML = new Date().getFullYear();
};
date();
}
the main idea is to get the number of the week between two dates (from a period of start date and end date)!
Something like that: if the period is 01-05-2020 to 31-05-2020 and in the data picker I chouse 08-05-2020 result will be 2, the second week.
can someone help with that can't figure out by my self,
thank you!
here is JS date picker code line with setting up period 01-05-2020 to 31-05-2020, how to echo out from this js code number of week for future php usage or input value?
js
<!-- js -->
<script src='https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js' type='text/javascript'></script>
<!-- Datepicker -->
<link href='https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.9.0/css/bootstrap-datepicker.min.css' rel='stylesheet' type='text/css'>
<script src='https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.9.0/js/bootstrap-datepicker.min.js' type='text/javascript'></script>
<script type="text/javascript">
$(document).ready(function(){
$('#datepicker').datepicker({
format: "dd/mm/yyyy",
startDate: new Date('2020-5-1'),
endDate: new Date('2020-5-31')
});
});
</script>
html
<div class="form-group">
<label for="formGroupExampleInput">Date of sale</label>
<input type="text" name="dos" value="<?php echo $doc; ?>" class="form-control" id='datepicker' id="formGroupExampleInput">
</div>
Accordingly to your main idea, you can use date-fns library to get the difference between date in weeks.
// import date-fns library
<script src="https://cdnjs.cloudflare.com/ajax/libs/date-fns/2.0.0-alpha0/date_fns.min.js"></script>
Then you can:
let diffCalendarWeeks = dateFns.differenceInCalendarWeeks(new Date(2020,4,31), new Date(2020,4,1));
let diffWeeks = dateFns.differenceInWeeks(new Date(2020,4,31), new Date(2020,4,1))
console.log(diffCalendarWeeks); //5
console.log(diffWeeks); // 4
See date-fns documentation
https://date-fns.org/v2.0.0-alpha.1/docs/differenceInCalendarWeeks
If you want to know the week number within specified month you can see the difference between the selected date and first date.
let selectedDate = new Date(2020, 4, 15);
let startOfMonth = dateFns.startOfMonth(new Date());
var selectedWeek = dateFns.differenceInWeeks(selectedDate, startOfMonth) + 1;
console.log(selectedWeek);
Or you can try this answer if fits you better
Getting current week of current month
Thanks, I found a solution to my problem.
Here it is, maybe someone needed..
<script>
function diff_weeks(dt2, dt1)
{
var diff =(dt2.getTime() - dt1.getTime()) / 1000;
diff /= (60 * 60 * 24 * 7);
return Math.abs(Math.round(diff));
}
dt1 = new Date(2014,10,2);
dt2 = new Date(2014,10,11);
console.log(diff_weeks(dt1, dt2));
dt1 = new Date("June 13, 2014 08:11:00");
dt2 = new Date("October 19, 2014 11:13:00");
console.log(diff_weeks(dt1, dt2));
<script>
lnk.
https://www.w3resource.com/javascript-exercises/javascript-date-exercise-47.php
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>
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>
I've got a rotating image that changes daily and I'm trying to make this the background image of a DIV so I can have a menu over it. For some reason it just displays all the information inside the includes file instead of showing the daily image?
<div styles="background-image: url(<?php include('includes/promotions.php'); ?>)">MENU</div>
Inside the includes file:
<SCRIPT LANGUAGE="JavaScript">
today = new Date();
day = today.getDay();
arday = new Array("images/daily-offers/sunday.png", "images/daily-offers/monday.png", "images/daily-offers/tuesday.png", "images/daily-offers/wednesday.png", "images/daily-offers/thursday.png", "images/daily-offers/friday.png", "images/daily-offers/saturday.png");
document.write("<img src='"+arday[day]+"'>");
</script>`
I'm kind of new to this but I appreciate the help!
You are trying to put javascript into the style attribute of a div, this isn't possible. Either you need to have php code come up with the filename instead of using an include, or you need to create the div give it an id the use javascript (outside the div's style) to change the background-image.
<div id='changeme'>Menu</div>
<SCRIPT LANGUAGE="JavaScript">
today = new Date();
day = today.getDay();
arday = new Array("images/daily-offers/sunday.png", "images/daily-offers/monday.png", "images/daily-offers/tuesday.png", "images/daily-offers/wednesday.png", "images/daily-offers/thursday.png", "images/daily-offers/friday.png", "images/daily-offers/saturday.png");
//ASSUMING YOU HAVE JQUERY
$('#changeme').css('background-image',arday[day]);
</SCRIPT>
Or simply use php:
<?php
$arday = array("images/daily-offers/sunday.png", "images/daily-offers/monday.png", "images/daily-offers/tuesday.png", "images/daily-offers/wednesday.png", "images/daily-offers/thursday.png", "images/daily-offers/friday.png", "images/daily-offers/saturday.png");
$day = date('w');
?>
<div styles="background-image: url('<?php echo $arday[$day]; ?>')">MENU</div>
Or if the naming convention of the images is always the same you could simply do:
<div styles="background-image: url('images/daily-offers/<?php echo strtolower(date('l')); ?>.png')">MENU</div>
You can set the backgroundImage like this:
document.getElementById("mymenu").style.backgroundImage="url(...)";
Your code could go like this:
<div id="mymenu">MENU</div>
<SCRIPT LANGUAGE="JavaScript">
today = new Date();
day = today.getDay();
arday = new Array("images/daily-offers/sunday.png", ...);
document.getElementById("mymenu").style.backgroundImage="url('"+arday[day]+"')";
</script>`
You can't execute javascript inside an attribute like that.
You could try this - change the contents of your includes/promotions.php file to the following:
<?php
$day = strtolower(date('l'));
echo '<img src="images/daily-offers/' . $day . '.png">';
?>
Additionally, the attribute on your div should be style, not styles.
I would not use PHP to do that.
I would right the following javascript code at the page where you showing right now the div with the background.
<div id="bgdiv">MENU</div>
<SCRIPT LANGUAGE="JavaScript">
today = new Date();
day = today.getDay();
arday = new Array("images/daily-offers/sunday.png", "images/daily-offers/monday.png", "images/daily-offers/tuesday.png", "images/daily-offers/wednesday.png", "images/daily-offers/thursday.png", "images/daily-offers/friday.png", "images/daily-offers/saturday.png");
document.getElementById('bgdiv').style.backgroundImage = "url(' + arday[day] + ')";
</script>