this is my javascript function to compare two dates but it canot work correctly
how to convert these character values to date format?
my code is
function dateCompare()
{
var fit_start_time = $("#datepicker_from").val();
var fit_end_time = $("#datepicker_to").val();
if((fit_start_time=="") || (fit_end_time==""))
{
alert ("Fill all fields");
}
else
{
if (fit_start_time > fit_end_time)
{
alert("invalid entry");
$('#datepicker_to').val('');
$('#datepicker_from').val('');
}
}
}
my html code is
<html>
<body>
<form name="form6" id="form6" action="invoice_date_all.php" method="post">
<div style="padding-top:4px;width:30px;float:left; ">From</div>
<div style="width:172px;float:left; ">
<input type="text" id="datepicker_from" name="datepicker_from" onchange="dateCompare();" size="15"/>
</div>
<div style="padding-top:4px;width:20px;float:left; "> To</div>
<div style="width:172px;float:left; ">
<input type="text" id="datepicker_to" name="datepicker_to" onchange="dateCompare();" size="15"/></div>
<div class="label3"><input type="submit" value="Invoice Print"/></a></div>
</form>
</body>
</html>
var fit_start_time = $("#datepicker_from").val();
var fit_end_time = $("#datepicker_to").val();
var a = fit_start_time.split('/');
var start = new Date(a[2], a[1] - 1, a[0]);
var b = fit_end_time.split('/');
var end = new Date(b[2], b[1] - 1, b[0]);
if (start > end) {
}
If your date separator is different than "/" then use your's in above code.
Related
I want to write a javascript that will calculate age from submittal date to today and if the item is more than 5days old will change color of text to yellow and red if its more than 10days old.
<p>text<p>
<input type="date" id="date" name="date">
<input type="submit" value="Submit">
<html>
<body>
<p>Your Age Calc<p>
<form method="GET">
<input type="date" id="date" name="date">
<button type="button" id="mybutton">Submit</button>
</form>
<div id="result"></div>
<script type="application/javascript">
function showResult() {
let result = document.getElementById("result")
let date = document.getElementById("date");
if (date.value === "" ) {
result.innerHTML = "Please input a correct date, 😅!";
} else {
let birthday = new Date (`${date.value}`)
let ageDifMs = Date.now() - birthday.getTime();
let num_days = ((ageDifMs % 31536000000) % 2628000000)/86400000;
num_days > 10 ? result.style.color = "green" : result.style.color = "blue"
result.innerHTML = "😆 Your age(days), " + num_days.toFixed(1);
}
}
document.getElementById("mybutton").onclick = showResult;
</script>
</body>
</html>
I have a function that gets the birthdate and don't print the output which is the sign according to the birthdate
I want the output to be under the send button (where id=output) currently works only with alert
another possibility is that the output will be in an input text.
Do you have any solution instead of alert as an output?
function yourSign() {
var signDate = $("input[name='birthDate']").val();
tempSignDate = signDate.split("-").join("/");
newSignDate = tempSignDate.substring(5, 10);
var AriesDateFrom = "21/03";
var AriesDateTo = "20/04";
var TaurusDateFrom = "21/04";
var TaurusDateTo = "20/05";
var Ad1 = AriesDateFrom.split("/");
var Ad2 = AriesDateTo.split("/");
var Td1 = TaurusDateFrom.split("/");
var Td2 = TaurusDateTo.split("/");
var s = newSignDate.split("/");
if (newSignDate == "") {
alert("enter birthday");
}else if (s >= Ad1 && s < Ad2) {
document.getElementById("output").innerHTML = "Aries";
}else if (s >= Td1 && s < Td2) {
document.getElementById("output").innerHTML = "Taurus";
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<head>
<meta charset="utf-8" />
<!--<script src="https://code.jquery.com/jquery-1.12.4.min.js"
integrity="sha256-ZosEbRLbNQzLpnKIkEdrPv7lOy9C27hHQ+Xp8a4MxAQ="
crossorigin="anonymous">
</script>-->
</head>
<body>
<div>
<form>
<label for=birthDate>birthdate</label><br /><input type="date" name="birthDate" id="birthDate" /><br />
<button onclick="yourSign()">send</button><br />
<label> your sign is </label><br />
<p id="output"></p>
<!--<input type="text" name="output" id="output" />-->
</form>
</div>
</body>
</html>
split() creates an array. You can not directly compare arrays as a whole.
Your arrays has two elements: day number and month number.
Day is always index 0 in your snippet.
Month is always index 1.
Try to compare your arrays in steps:
if ( s[1] >= Ad1[1] && s[0] >= Ad[0] && s[1] <= Ad2[1] && s[0] <= Ad2[0]) { [...] };
This question already has answers here:
Compare two dates with JavaScript
(44 answers)
Why does Date.parse give incorrect results?
(11 answers)
Closed 5 years ago.
In below Code i want to validate date between 02/08/2017 and 05/08/2017 and give us a alert which is Date is not in range
<script type="text/javascript">
function validate()
{
today = new Date();
fromdt= new Date("02/08/2017");
todate=new Date("05/08/2017");
if( document.myForm.entrydt.value == "" )
{
alert( "Please Select Entry Date!" );
document.myForm.entrydt.focus() ;
return false;
}
else if(!document.myForm.entrydt.value.match(letters3))
{
alert("Entry Date: Enter Only Date Format i.e DD/MM/YYYY");
document.myForm.entrydt.focus() ;
return false;
}
else if (!document.myForm.entrydt.value.today > startdt && !document.myForm.entrydt.value.today < todate)
{
alert("Entry Date: Enter Date in Proper Range");
document.myForm.entrydt.focus() ;
return false;
}
return( true );
}
</script>
==============================================================================
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" class="form-inline" role="form" name="myForm" id="myForm" onsubmit="return(validate());">
<div id="" class="container" >
<div class="form-group">
<label for="entrydt">Entry Date</label>=
<input class="form-control" style='font-weight:bold;text-transform:uppercase;' id="entrydt" type="text" name="entrydt" style='' placeholder="DD/MM/YYYY" value="" size="10">
</div>
</div>
</form>
new Date().getTime() will give time in milliseconds as long value number to compare values
var today = new Date().getTime(); // 1501653935994
var from = new Date("02/08/2017").getTime(); // gives 1486492200000
var to = new Date("05/08/2017").getTime();
if(today >= from && today <= to) {
// your code goes here
}
new Date().getTime()
gives you the timestamp in ms.
var today = new Date().getTime();
var from = new Date("02/08/2017").getTime();
var to = new Date("05/08/2017").getTime();
var withinRange = today >= from && today <= to;
document.getElementById gets the element (i.e p tag) but as soon as
it writes in it the content disappears. There is no error on console but whatever is written within p tag disappears as soon as anything is written onto the p tag.
I can't find any reason for it not working also i'am not allowed to use php for accepting form inputs.
var d=new Date();
var cday=d.getDay();
var cmonth=d.getMonth();
var cyear=d.getFullYear();
var day,month,year,dage,mage,yage;
function getDOB() {
var DOB = new Date(document.getElementById("DOB").value);
year = DOB.getFullYear();
month = DOB.getMonth();
day = DOB.getDay();
}
document.getElementById("inp").onclick = function execute() {
getDOB();
yage = cyear - year;
if (cmonth >= month) {
mage = cmonth - month;
} else {
mage = 12 - (month - cmonth);
yage = yage - 1;
}
if (cday >= day) {
dage = cday - day;
} else {
mage = mage - 1
dage = 30 - (day - cday);
}
document.getElementById("output").innerHTML = "your age is " + dage + " days " + mage + " months " + yage + " years";
}
<html>
<head>
</head>
<body>
<p id="month">
</p>
<form id="form">
<!input type="text" id="day" placeholder="dd">
<! input type="text" id="day" placeholder="mm">
<!input type="text" id="day" placeholder="yyyy">
<input type="date" id="DOB">
<button id="inp">submit</button>
<br>
</form>
<p id="output"></p>
<script src="age.js"></script>
</body>
</html>
Your code contains earlier errors and could not reach the innerHTML yet.
Here's the error to start with:
Uncaught ReferenceError: cyear is not defined
You'll also have to add return false; to the end of the function to prevent the form from submitting, as stated by #thewatcheruatu.
date=new Date(); // Get current date
cyear=date.getFullYear(); // current year
cmonth=date.getMonth()+1; // current month
cday=date.getDate(); // current day
function getDOB()
{
var DOB=new Date(document.getElementById("DOB").value);
year=DOB.getFullYear();
month=DOB.getMonth();
day=DOB.getDate(); // getDate() function returns the current date
}
function execute()
{
getDOB();
yage=cyear-year;
if( cmonth>=month)
{
mage=cmonth-month;
}
else
{
mage=12-(month-cmonth);
yage=yage-1;
}
if ( cday>=day )
{
dage=cday-day;
}
else
{
mage=mage-1
dage=30-(day-cday);
}
document.getElementById("output").innerHTML="your age is "+dage+" days "+mage+" months "+yage+ " years";
}
<html>
<head>
</head>
<body>
<p id="month">
</p>
<form id="form">
<!input type="text" id="day" placeholder="dd">
<! input type="text" id="day" placeholder="mm">
<!input type="text" id="day" placeholder="yyyy">
<input type="date" id="DOB">
<button type="button" id="inp" onclick="execute()">submit</button><br>
</form>
<p id="output"></p>
<script src="age.js"></script>
</body>
</html>
I am making a simple Goal-traking completely offline HTML5 app using localStorage.
The problem that I am facing is, that, Retrieving JSON data is working completely fine in a separate file but not when put together as a part of a bigger system.
I would have kept it in a seperate file and would have stopped worrying about it, but I can't do that because of same-origin policy.
Here is the code that's working fine as a seperate file:
<HTML>
<HEAD>
</HEAD>
<BODY>
<script type="text/javascript">
window.onload = function(){
// setup
var goal = "CN";
var date2 = new Date();
var diff = 0;
var active = true;http://jsfiddle.net/#save
var data = '{"goals": [{"goal":"' + goal + '","duedate":"'
+ date2 + '","noofdays":"' + diff + '","active":"'
+ active + '"}]}';
localStorage.setItem("goals",data);
// test
var goalsStr = localStorage.getItem("goals");
var goalsObj = JSON.parse(goalsStr);
for (i=0; i<goalsObj.goals.length; i++) {
if(goal==goalsObj.goals[i].goal) {
document.body.appendChild(document.createTextNode(
"The goal is " + JSON.stringify(goalsObj.goals[i])));
}
}
}
</script>
</BODY>
</HTML>
and now here is the code that is supposed to work, as all of it's different parts are working fine, all the syntax is correct, but still it is giving absolutely no output:
<HTML>
<HEAD>
</HEAD>
<BODY>
<script type="text/javascript">
function save()
{
//Get data from the form
var goal = document.getElementById("goal").value; //Get 'goal' from form
var date2 = document.getElementById("date2").value; //Get 'duedate' from the form
var active = document.getElementById("active").value; //Get 'active' from form
//Calculating the number of days remaining
var date1 = new Date(); //Current Date and Time
var dd = date1.getDate(); //Current Date
var mm = date1.getMonth()+1; //January is 0!
var yyyy = date1.getFullYear(); //Current Year
if(dd<10){dd='0'+dd} if(mm<10){mm='0'+mm} date1 = mm+'/'+dd+'/'+yyyy; //Parsing the date to the required format
var diff = Math.floor(( Date.parse(date2) - Date.parse(date1) ) / 86400000); //Calculate no. of days remaining
if (localStorage.getItem('gcount') === null) {
localStorage.setItem('gcount', "1");
var data = '{"goals":[{"goal":"'+goal+'","duedate":"'+date2+'","noofdays":"'+diff+'","active":"'+active+'"}]}';
localStorage.setItem("goals",data);
//document.getElementById("temp").innerHTML="first";
}
else{
var goalsStr = localStorage.getItem("goals");
var goalsObj = JSON.parse(goalsStr);
var goal = "CN"
var data = { "goal": goal, "duedate": date2, "noofdays": diff, "active": active};
goalsObj.goals.push(data);
localStorage.setItem("goals", JSON.stringify(goalsObj));
}
}
function load(){
/* // setup
var goal = "CN";
var date2 = new Date();
var diff = 0;
var active = true;http://jsfiddle.net/#save
var data = '{"goals": [{"goal":"' + goal + '","duedate":"'
+ date2 + '","noofdays":"' + diff + '","active":"'
+ active + '"}]}';
localStorage.setItem("goals",data); */
// test
var goalsStr = localStorage.getItem("goals");
var goalsObj = JSON.parse(goalsStr);
for (i=0; i<goalsObj.goals.length; i++) {
if(goal==goalsObj.goals[i].goal) {
document.getElementById("duedate").innerHTML=goalsObj.goals[i].duedate;
document.getElementById("noofdays").innerHTML=goalsObj.goals[i].noofdays;
document.getElementById("active").innerHTML=goalsObj.goals[i].active;
// document.body.appendChild(document.createTextNode("The goal is " + JSON.stringify(goalsObj.goals[i])));
}
}
}
</script>
<form name="input" onsubmit="save(); return false;">
<label>Goal: </label> <input type="text" name="goal" id="goal"><br>
<label>Due Date: </label> <input type="date" name="date2" id="date2"></span><br>
<label>Active: </label><br>
<input type="radio" name="active" id="active" value="Future">Future <br>
<input type="radio" name="active" id="active" value="Present">Present <br> <br>
<!-- Submit button to submit the form -->
<input type="submit" value="submit">
</form>
<form name="load" onsubmit="load(); return false;">
<label>Goal: </label> <input type="text" name="goal" id="goal"><br>
<input type="submit" value="submit">
<p id="temp"></p>
<p id="temp1"></p>
<p id="temp2"></p>
<p id="temp3"></p>
<p id="temp4"></p>
<p id="temp5"></p>
<p id="temp6"></p>
<p id="temp7"></p>
<p id="temp8"></p>
<p id="duedate"></p>
<p id="noofdays"></p>
<p id="active"></p>
</BODY>
</HTML>
I am getting the error that object is not a function. I have tried all other similar questions on StackOverflow and nothing worked.
What's wrong? What should I do?
You are using the same id for multiple different elements.
Also, try using IndexedDB instead of localStorage.