Here is my code,
function getDateonperiod(elem)
{
var periodval=$("#period"+elem).val();
var days = periodval * 30;
var startDate=new Date();
var endDate = new Date();
endDate.setDate(endDate.getDate() + days);
var strDate = startDate.getFullYear() + "-" + (startDate.getMonth()+1) + "-" + startDate.getDate();
$("#from_date"+elem).val(strDate);
$("#to_date"+elem).val((endDate.getFullYear()+'-'+endDate.getMonth() + 1)+'-'+endDate.getDate());
}
Onchange input field value getting number of days days. I'm getting start date correctly but end date if input value 1 its working fine but its more than one its returning like this 2016-11-27 2016-21-28 from current date. How to fix this?
You missed a parenthesis:
endDate.getFullYear()+'-'+(endDate.getMonth() + 1)+'-'+endDate.getDate();
Try this:
$( "#period" ).change(function() {
var periodval=$("#period").val();
var days = periodval * 30;
var startDate=new Date();
var endDate = new Date();
endDate.setDate(endDate.getDate() + days);
var strDate = startDate.getFullYear() + "-" + (startDate.getMonth()+1) + "-" + startDate.getDate();
$("#from_date").val(strDate);
$("#to_date").val(endDate.getFullYear()+'-'+(endDate.getMonth() + 1)+'-'+endDate.getDate());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="number" id="period" />
<input type="text" id="from_date" />
<input type="text" id="to_date" />
you can use moment.js here
var days = 10;
var dateFormat = 'YYYY-MM-DD';
var startFormatted = moment().format(dateFormat);
var endFormatted = moment().add(days, 'day').format(dateFormat);
console.log(startFormatted)
console.log(endFormatted)
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.10.6/moment.min.js"></script>
<script src="https://getfirebug.com/firebug-lite-debug.js"></script>
You are not adding days correctly.
function getDateonperiod(elem)
{
var periodval=$("#period"+elem).val();
var days = periodval * 30;
var startDate=new Date();
var endDate = new Date(startDate.getFullYear(),startDate.getMonth(),startDate.getDate()+n);
var strDate = startDate.getFullYear() + "-" + (startDate.getMonth()+1) + "-" + startDate.getDate();
$("#from_date"+elem).val(strDate);
$("#to_date"+elem).val((endDate.getFullYear()+'-'+endDate.getMonth() + 1)+'-'+endDate.getDate());
}
Simply use this library
http://momentjs.com/
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.10.6/moment.min.js">
Your code with momentjs
function getDateonperiod(elem)
{
var periodval=$("#period"+elem).val();
var days = periodval * 30;
var startDate = new moment();
var endDate = new moment();
endDate.add(days,'days');
var strStartDate = startDate.format("YYYY - MM - DD");
var strEndDate = endDate.format("YYYY - MM - DD");
$("#from_date"+elem).val(strDate);
$("#to_date"+elem).val(strEndDate);
}
I just extended Date function for adding days. This may help you:
Date.prototype.addDays = function(days) {
this.setDate(this.getDate() + parseInt(days));
return this;
};
$("#period").change(function() {
var periodval = $("#period").val();
var days = periodval;
var startDate = new Date();
var endDate = new Date();
endDate.addDays(days);
//endDate.setDate(endDate.getDate() + days);
var strDate = startDate.getFullYear() + "-" + (startDate.getMonth() + 1) + "-" + startDate.getDate();
$("#from_date").val(strDate);
$("#to_date").val(endDate.getFullYear() + '-' + (endDate.getMonth() + 1) + '-' + endDate.getDate());
});
Related
I just tried to make a span with formatted date under foreach using knockout
I have this script
Date.prototype.toFormattedDate = function () {
var dd = this.getDate();
if (dd < 10) dd = '0' + dd;
var mm = this.getMonth() + 1;
if (mm < 10) mm = '0' + mm;
var yyyy = this.getFullYear();
/* change format here */
return String(dd + "/" + mm + "/" + yyyy);
};
and in html i try this
<span class="form-control" data-bind="text: new Date(my_date).toFormattedDate() " />
my_date is a string date "2020-09-13T00:00:00"
but it always shows NaN/NaN/NaN
i tried to use moment.js but it gave me "Invalid date"
Demo:
Date.prototype.toFormattedDate = function() {
var dd = this.getDate();
if (dd < 10) dd = '0' + dd;
var mm = this.getMonth() + 1;
if (mm < 10) mm = '0' + mm;
var yyyy = this.getFullYear();
/* change format here */
return String(dd + "/" + mm + "/" + yyyy);
};
const formatted = new Date("2020-09-13T00:00:00").toFormattedDate();
console.log(formatted)
It's happening because my_date is an observable. new Date(my_date) will try to convert the observable to a date and it fails. So, get the value in the observable by using my_date() and use it in the new Date() constructor
Date.prototype.toFormattedDate = function(){var a=this.getDate();if(a<10){a="0"+a}var b=this.getMonth()+1;if(b<10){b="0"+b}var c=this.getFullYear();return String(a+"/"+b+"/"+c)};
ko.applyBindings({ my_date: ko.observable('2020-09-13T00:00:00') })
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<span class="form-control" data-bind="text: new Date(my_date()).toFormattedDate() " />
Another option is to create a custom binding for your date format. You could move all the date format code to the custom binding directly if you don't want to pollute Date.prototype
function customDateHandler(element, valueAccessor) {
var value = ko.unwrap(valueAccessor());
element.textContent = new Date(value).toFormattedDate()
}
ko.bindingHandlers.customDateFormat = {
init: customDateHandler,
update: customDateHandler
};
And use the binding in your span:
<span class="form-control" data-bind="customDateFormat: my_date" />
Here's a snippet:
function customDateHandler(element, valueAccessor) {
var value = ko.unwrap(valueAccessor());
element.textContent = new Date(value).toFormattedDate()
}
ko.bindingHandlers.customDateFormat = {
init: customDateHandler,
update: customDateHandler
};
Date.prototype.toFormattedDate = function(){var a=this.getDate();if(a<10){a="0"+a}var b=this.getMonth()+1;if(b<10){b="0"+b}var c=this.getFullYear();return String(a+"/"+b+"/"+c)};
ko.applyBindings({ my_date: ko.observable('2020-09-13') })
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<span class="form-control" data-bind="customDateFormat: my_date" />
What am I doing wrong here I am trying to get the current date to be in the input box, however if I change the date I want the new value to be there?
But currently no matter what date I enter it outputs the current date.
function display_array() {
////////////Date convert
var d = new Date();
var mm = d.getMonth() + 1;
var dd = d.getDate();
var yy = d.getFullYear();
var Dateissue = mm + '/' + dd + '/' + yy; //(US)
document.getElementById("DateissueO").innerHTML = "Date of issue: " + Dateissue;
var Dateissue = document.getElementById("DateissueO").value;
}
window.onload = function() {
document.getElementById('Dateissue').value = new Date().toLocaleDateString('en-CA')
}
<INPUT id="button" onclick="display_array();" class="button" type="button" value="Submit">
Date of Issue: <INPUT name="Dateissue" id="Dateissue" type="date">
<DIV id="DateissueO"></DIV>
You need to initialize your Date object with the selected date.
Get the new date from element Dateissue and convert it to the compatible date format for new Date(YYYY/MM/DD) constructor.
document.getElementById('Dateissue').value.replace(/-/g, '/')
Look at this code snippet
function display_array() {
////////////Date convert
var d = new Date(document.getElementById('Dateissue').value.replace(/-/g, '/'));
var mm = d.getMonth() + 1;
var dd = d.getDate();
var yy = d.getFullYear();
var Dateissue = mm + '/' + dd + '/' + yy; //(US)
document.getElementById("DateissueO").innerHTML = "Date of issue: " + Dateissue;
var Dateissue = document.getElementById("DateissueO").value;
}
window.onload = function() {
document.getElementById('Dateissue').value = new Date().toLocaleDateString('en-CA')
}
<INPUT id="button" onclick="display_array();" class="button" type="button" value="Submit">
Date of Issue: <INPUT name="Dateissue" id="Dateissue" type="date">
<DIV id="DateissueO"></DIV>
See? now is using the new selected date from field Dateissue.
I have a function:
function loadDefaultDate(){
var currentDate = new Date();
var curYear, curMonth, curDay;
curYear = currentDate.getFullYear();
curMonth = ("0" + (currentDate.getMonth() + 1)).slice(-2);
curDay = ("0" + currentDate.getDate()).slice(-2);
document.getElementById("startDate").value = curYear + "-" + curMonth + "-" + curDay;
}
And html form input:
<input type=text name="startDate" size=10 maxlength=10 onload="loadDefaultDate()" onclick="javascript:resetValues();">
Why I am not getting default date when page loads?
Try with this:
function load() {
console.log("load event detected!");
}
window.onload = load;
Your input has name="startDate", but you are trying to look it up by Id.
Set the proper Id on your input.
<input type=text name="startDate" id="startDate" size=10 maxlength=10 onclick="javascript:resetValues();">
I also manually called loadDefaultDate in javascript. As adeneo's comment mentions, onload does not work with input elements.
function loadDefaultDate(){
var currentDate = new Date();
var curYear, curMonth, curDay;
curYear = currentDate.getFullYear();
curMonth = ("0" + (currentDate.getMonth() + 1)).slice(-2);
curDay = ("0" + currentDate.getDate()).slice(-2);
document.getElementById("startDate").value = curYear + "-" + curMonth + "-" + curDay;
}
loadDefaultDate();
How to check time conditionin Jquery
var startTime="20:02:55"; // or 12:34
var endTime ="21:02:55" // or 1:34
var dt = new Date();
var time = dt.getHours() + ":" + dt.getMinutes() + ":" + dt.getSeconds();
if(time >startTime || time < endTiime){
$("#a").html("show Box");
}else{
$("#a").html("Expire BOx");
}
How to check 12 hour and 24 hour condition also?
is it correct? i need am, pm format check please can anyone help me?
Here is some code. I am appending to show both behaviour.
Here is DEMO
test("20:02:55", "21:02:55");
test("13:02:55", "15:02:55");
function test(start_time, end_time) {
var dt = new Date();
//convert both time into timestamp
var stt = new Date((dt.getMonth() + 1) + "/" + dt.getDate() + "/" + dt.getFullYear() + " " + start_time);
stt = stt.getTime();
var endt = new Date((dt.getMonth() + 1) + "/" + dt.getDate() + "/" + dt.getFullYear() + " " + end_time);
endt = endt.getTime();
var time = dt.getTime();
if (time > stt && time < endt) {
$("#a").append("<br> show Box ");
} else {
$("#a").append("<br> Expire BOx ");
}
}
Try this.
I took the logic to print 'Show Box' if the current time is in between the start and end time. else viceversa.
var startTime="20:02:55"; // or 12:34
var endTime ="21:02:55" // or 1:34
var dt = new Date();
var st = new Date('00','00','00',startTime.split(':')[0],startTime.split(':')[1],startTime.split(':')[2]);
var et = new Date('00','00','00',endTime.split(':')[0],endTime.split(':')[1],endTime.split(':')[2]);
if(dt.getTime() >st.getTime() && dt.getTime() < et.getTime()){
alert("show Box");
}else{
alert("Expire BOx");
}
Supposedly, I should be able to create an arbitrary date using the Date constructor as demonstrated here and referenced here
Where am I going wrong? Please notice that on the last few lines of prettyDateToTimeStamp, I modify the month and day to verify that the Date constructor is doing something - but it is not noticing anything I pass in and just returns the current date.
Here is my code below: and a jsfiddle
<!DOCTYPE html>
<html>
<body>
<p id="demo">Click the button to display the full year of todays date.</p>
<p id="demo2">todays date.</p>
<p id="demo3">some other date.</p>
<button onclick="showdates()">Try it</button>
<script>
function showdates() {
var d = Date.now();
var dv = document.getElementById('demo');
dv.innerHTML = d;
var pd = prettyDate(d);
dv = document.getElementById('demo2');
dv.innerHTML = pd;
var ts = prettyDateToTimeStamp(pd);
dv = document.getElementById('demo3');
dv.innerHTML = ts;
}
function prettyDate(javaScriptTimeStamp) {
var dt = new Date(javaScriptTimeStamp);
var year = dt.getFullYear();
var month = dt.getMonth() + 1;
var day = dt.getDate();
var hours = dt.getHours();
var minutes = dt.getMinutes();
var seconds = dt.getSeconds();
return month + "/" + day + "/" + year + " " + hours + ":" + minutes + ":" + seconds;
}
function prettyDateToTimeStamp(prettyDate) {
var halves = prettyDate.split(' ');
console.log("halves: " + halves);
var calpart = halves[0];
console.log("calpart : " + calpart );
var clockpart = halves[1];
console.log("clockpart : " + clockpart );
var calbits = calpart.split('/');
console.log("calbits : " + calbits );
var timebits = clockpart.split(':');
console.log("timebits : " + timebits );
var year = parseInt(calbits[2],10);
console.log("year : " + year );
var month = parseInt(calbits[0],10);
console.log("month : " + month );
var day = parseInt(calbits[1],10);
console.log("day : " + day );
var hour = parseInt(timebits[0],10);
console.log("hour : " + hour );
var min = parseInt(timebits[1],10);
console.log("min : " + min );
var sec = parseInt(timebits[2],10);
console.log("sec : " + sec );
month += 3; // change month radically to demonstrate the problem
console.log("month is now: " + month );
day += 7; // change day too
console.log("day is now: " + day );
var ts = Date(year,month,day,hour,min,sec,0);
console.log("ts : " + ts ); // date ctor paramters completely ignored...?
return ts;
}
</script>
</body>
</html>
omg, I have to say "new" Date .... (I've been using Python too much lately)
corrected code now works.
function prettyDateToTimeStamp(prettyDate) {
var halves = prettyDate.split(' ');
var calpart = halves[0];
var clockpart = halves[1];
var calbits = calpart.split('/');
var timebits = clockpart.split(':');
var year = parseInt(calbits[2],10);
var month = parseInt(calbits[0],10);
var day = parseInt(calbits[1],10);
var hour = parseInt(timebits[0],10);
var min = parseInt(timebits[1],10);
var sec = parseInt(timebits[2],10);
month += 3; // change month radically to demonstrate the problem
day += 7; // change day too
var ts = new Date(year,month,day,hour,min,sec,0); // you have to use NEW here!
return ts;
}