i have problem with date validation in javascript
the problem is i have popup calendar the return a date value
i want to check the date in javascript before send it to parent page
in popup calendar.aspx
function passDateValue(DateValue)
{
window.returnValue=DateValue;
window.close();
return false;
}
in popup calendar codebehind
ClientScript.RegisterStartupScript(GetType(), "SelectDate", "passDateValue('" + clrPopUp.SelectedDate.ToShortDateString() + "')", true);
the function that call the popup calendar and check the returned value
function Calendar_popup(tbClientID)
{
var today = new Date();
var Day = today.getDate();
var Month = today.getMonth()+1;
var Year = today.getFullYear();
if(Month<10){Month = '0'+Month;}
if(Day<10){Day = '0'+Day;}
var todayFormat = Day + "/" + Month + "/" + Year;
datevalue = window.showModalDialog("Calendar_Dialog.aspx?ctlid=" + tbClientID, '',"dialogHeight:250px;dialogWidth:300px;");
var startdate = Date.parse(datevalue);
var enddate = Date.parse(todayFormat);
if (startdate>enddate)
{alert('BirthDate Must be less than today');
return;
}
}
is there anyway to check date ?
thanks!
Check out date.js, specifically...
http://code.google.com/p/datejs/wiki/APIDocumentation#compare
Compares the first date to the second date and returns an number
indication of their relative values. -1 = this is < date. 0 =
values are equal. 1 = this is > date.
The isAfter() and the isBefore() methods might be useful for your problem :)
Download the library here:
http://code.google.com/p/datejs/downloads/detail?name=date.js&can=2&q=
Related
I have a date string in JavaScript which is arranged in a particular manner. How do I rearrange this in order to fit standard time?
let date = "2020-06-01T00:00:00Z"
How do I rearrange the date variable in order to match the format MM/DD, YYYY ?
Change your code to as follows:
let date = "2020-06-01T00:00:00Z";
date = new Date(date);
var dd = date.getDate();
var mm = date.getMonth()+1;
var yyyy = date.getFullYear();
if(dd<10){dd='0'+dd}
if(mm<10){mm='0'+mm};
console.log(mm+'/'+dd+', '+yyyy)
i don't real know this is possible but i found the function you can use instead
function GetFormattedDate() {
var todayTime = new Date();
var month = todayTime.getMonth() + 1;
var day = todayTime.getDate();
var year = todayTime.getFullYear();
return month + "/" + day + "/" + year;
}
console.log(GetFormattedDate());
so you can add more in the function or edit what the function will return as a format according to your will
I'm using the TimeIt code on my site, it can be found here: http://codegen.in/timeit/
This is the direct link to the code: https://res.cloudinary.com/vsevolodts/raw/upload/v1503371762/timeit.min.js
It looks like this:
//version 3. 2017-08-13
function timeit() {
var next_run_array = []; //array of dates/time on a page used to rerun function if a change should happen during the session
var curDate = new Date();
Date.prototype.yyyymmdd = function() {
var mm = this.getMonth() + 1;
var dd = this.getDate();
return [this.getFullYear(),
(mm > 9 ? '' : '0') + mm,
(dd > 9 ? '' : '0') + dd
].join('-');
};
var curDateYMD = curDate.yyyymmdd();
$('.timeit').each(function() {
var end = $(this).data('end'),
start = $(this).data('start');
//check if date or time value has valid format and push it to the list of refresh anchors
var startDate = checkdate(start, this);
var endDate = checkdate(end, this);
nextrun(startDate);
nextrun(endDate);
//add a datetime when the page needs to be refreshed (now+24 hrs time span only)
function nextrun(date) {
var nextruntimeout = date - curDate;
if (nextruntimeout < 1000 * 60 * 60 * 24 && nextruntimeout > 1000) {
next_run_array.push(nextruntimeout);
}
}
// Main Function
//check if the evend outside of a desired time span
if (((startDate < endDate) && (startDate > curDate || endDate < curDate)) ||
((startDate > endDate) && (startDate >= curDate) && (endDate <= curDate))
) {
$(this).addClass('hidden');
} else {
$(this).removeClass('hidden');
}
//Support Functions
//correct data creation from a string. accepted format YYYY-MM-DD HH:MM
function parseISO8601(d) {
var isoExp = /^\s*(\d{4})-(\d\d)-(\d\d)?.(\d\d)?.(\d\d)\s*$/,
date = new Date(NaN),
datenew,
month,
dateString=d.substr(0, d.indexOf(' '));
parts = isoExp.exec(d);
if(parts) {
month = +parts[2];
date.setFullYear(parts[1], month - 1, parts[3]);
if(month != date.getMonth() + 1) {
date.setTime(NaN);
}
date = new Date(parts[1], month - 1, parts[3], parts[4], parts[5])
}
return date;
}
//unification of the date string to the format YYYY-MM-DD HH:MM
function checkdate(date, obj) {
if (date) {
//check if only time is set (HH:MM); if so, add today's date
if (String(date).length < 6 && String(date).indexOf(":") > -1) {
date = curDateYMD + ' ' + String(date);
}
//check if only date is set; if so add 00:00 to the end of date
if (String(date).indexOf(":") == -1) {
date = date + ' 00:00';
}
//check if date is valid (avoid valid time)
var res = date.split(":"),
h = String(res.slice(0, 1)),
hours = h.substr(h.length - 2),
minutes = res.slice(1);
var timetest = (hours < 24 && minutes < 60) ? true : false;
//check if date is could be created from a value; if fails try to parse a string to a format
var returndate = new Date(date);
if (returndate == 'Invalid Date') {
var returndate = parseISO8601(date);
};
if (returndate == 'Invalid Date' || !timetest) {
//highlight the element if the is an error. use own \.error class if needed
$(obj).addClass("error").attr('title', '"' + date + '" date is incorrect; please use YYYY-MM-DD HH:MM format');
}
return returndate.getTime();
} else {
//if datetime is not set, just return current date-time
return curDate.getTime();
}
}
});
/* Schedule next runs */
if (next_run_array.length > 0) {
var nextruntime = Math.min.apply(null, next_run_array);
console.log("next run of timeit function is in " + nextruntime / 1000 + "seconds");
setTimeout(function() {
timeit();
}, nextruntime);
}
}
timeit();
(
Then you just put the embed code:
<div class="timeit" data-start="2019-02-15" data-end="2019-07-25 23:59">
This content will be shown between 2019-02-15 - 2019-07-25
</div>...<script src="/js/timeit.js"></script>
The idea is: my content is being shown between a certain period of time. I would like it to work with the UTC time zone, but right now the code is getting the date/hour info from the user's local time zone. So my content becomes available for example not at 8 AM UTC, but at 8 AM of the user's local time zone. I would like to change that.
I really, really tried to work this out on my own, but I guess this is beyond my skill set (which is pretty low). I'm confused by all the info about those ISO 8601, new Date, Date, I can't really find where it says "get the time from this source" to replace it with "get it from UTC". So - if any of you would just take a look at it and tell me what to put where, I would be extremely grateful.
Thank you all for your time!
Since you can't use server-side scripting because of Weebly... You will have to rely on the client's clock which can be tweeked. And the hidden class can easily be removed... But it seems you don't have the choice.
Now, I will suggest you to forget about the TimeIT plugin.
When it comes to dates in JavaScript/jQuery, I always recommand the use of moment.js which is really easy to use (you won't have to perform complex caluculations anymore) and fully documented, so you can do whatever you wish.
Here, content hiding based on start/end dates in data attributes would look like this:
$(document).ready(function(){
var utc_date = moment().utc().format("YYYY-MM-DD HH:mm"); // Client's date/time in UTC
$(".timeit").each(function(){
var start = moment($(this).data("start")).format("YYYY-MM-DD HH:mm");
var end = moment($(this).data("end")).format("YYYY-MM-DD HH:mm");
console.log((utc_date>start && utc_date<end)?"Content displayed":"Content hidden");
$(this).addClass("hidden"); // Hide content by default
if(utc_date>start && utc_date<end){
$(this).removeClass("hidden"); // Show content if now is between start/end dates
}
});
}); // ready
.hidden{
display:none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>
<div class="timeit" data-start="2019-02-15" data-end="2019-07-25 23:59">
This content will be shown between the dates in data attributes
</div>
You can try it in CodePen... Change the start date and hit "Run". I left some console logs so you can understand what is going on.
For more, explore moment.js documentation.
Users want to use the following formats to enter dates:-
mm-dd-yyyy OR yyyy-mm-dd OR m-d-yy OR m-d-yyyy OR mm/dd/yyyy OR m/d/yy.
My plan is to capture whatever they enter and convert it to yyyy-mm-dd because that is the format that the date field value must be submitted. They have refused to use a calendar . I have tried the following JS function without any success. Any ideas?
var value = ctrl.getValue();
var date_input = new Date(value);
var day = date_input.getDay();
var month = date_input.getMonth() + 1;
var year = date_input.getFullYear();
var yyyy_MM_dd = year + "-" + month + "-" + day;
return yyyy_MM_dd
Because its wrong to use var day = date_input.getDay();
use it like this
var day = date_input.getDate();
function getDateFormat(value){
var date_input = new Date(value);
var day = date_input.getDate();
var month = date_input.getMonth() + 1;
var year = date_input.getFullYear();
var yyyy_MM_dd = year + "-" + month + "-" + day;
return yyyy_MM_dd;
}
console.log(getDateFormat("2017-12-30"));
console.log(getDateFormat("12-30-2017"));
.getDay is giving you days of weeks
Also be sure to use date format accepted by Date
This question already has answers here:
Compare two dates with JavaScript
(44 answers)
Closed 6 years ago.
I have pretty extensively researched this issue, and I've found some useful information, but I haven't been able to solve my problem. All I'm trying to do is parse a date and compare it to another date. Seems simple, right? Here is what I've tried:
function getCurrentDate() { //this function simply returns today's date
var today = new Date();
var dd = today.getDate();
var mm = today.getMonth() + 1;
var yyyy = today.getFullYear();
if (dd < 10) {
dd = '0' + dd
}
if (mm < 10) {
mm = '0' + mm
}
today = mm + '/' + dd + '/' + yyyy;
return today;
}
$("#TxtDate").blur(function () {
var projectDueDate = Date.parse($("#lblDueDate").val()); //parses the project due date label to create a date variable
var itemDueDate = new Date($("#TxtDate").val()); //parses the value the user entered into the due date box to create a date variable
var actualProjectDueDate = new Date(projectDueDate);
if (Date.parse(document.getElementById('TxtDate').value) > getCurrentDate()) {
alert("The date you entered precedes today's date. Please enter a valid date.");
$("#TxtDate").val() = "";
}
});
The if statement isn't working in the TxtDate blur function. It is not showing the alert window, even though I am entering a date that precedes today's date. As you can see, I've tried some different things. Any suggestions?
Your function getCurrentDate is returning a string not a date object and you are comparing it with date object. So you need to parse the return value of getCurrentDate.
if (Date.parse(document.getElementById('TxtDate').value) > Date.parse( getCurrentDate())) {
alert("The date you entered precedes today's date. Please enter a valid date.");
$("#TxtLeaveFrom").val() = "";
}
Date.parse() returns a date object while getCurrentDate() returns a string. Add the Date.parse() there too:
if (Date.parse(document.getElementById('TxtDate').value) > Date.parse(getCurrentDate()))
I am having an input date field in my form. In my date field
i need to alert an error if the input date is greater than any date i define before
here is what i code :
$(document).ready(function () {
var date = new Date(2016,2,1); //the defined date is 1 March 2016
var day = date.getDate();
var month = date.getMonth();
month = month + 1;
if(day < 10){
day = '0' + day;
}
if(month < 10){
month='0'+month;
}
someday = day + '/' + month + '/' + date.getFullYear();
$("#q1 input").blur(function(){ //#q1 is the ID for the input field.
if($('#q1 input').val() > someday){
alert('the input is bigger than the defined');
}else{
alert('the defined is bigger than the input ');
}
});
});
To compare Dates is very straight forward. Most operators coerce the operands to number, and Dates return their time value so to see if today is before or after say 1 March 2016, create two Dates and compare them:
var epoch = new Date(2016,2,1); // Create date for 2016-03-01T00:00:00
var now = new Date(); // Create a date for the current instant
now.setHours(0,0,0,0); // Set time to 00:00:00.000
if (now < epoch) {
alert('Before 1 March, 2016');
} else {
alert('On or after 1 March, 2016');
}
Or a bit more compact:
alert((now < epoch? 'Before':'On or after') + ' 1 March, 2016');
You might want to compare the values as in the date form, not the way you did.
Convert the input value into the form of date and compare it with the variable 'date'.
Compare the input date with the desired date that you defined. For example:
var d1 = new Date();
var d2 = new Date(d1);
var same = d1.getTime() === d2.getTime();
var notSame = d1.getTime() !== d2.getTime();
If you find it tricky, then there is an awesome js library called moment.js. It is very useful when playing with dates.
$(document).ready(function () {
var date=new Date(2016,2,1); //the defined date is 1 March 2016
var fixedDate = returnDate(date);// convert date in dd/mm/yyyy format
//#q1 input will search a child input inside an #q1 dom element, which probably not the case
// input#q1 will refer to input with id #q1
// You can directly query the input since it has id #q1 so #q1 input is not correct
$("#q1").blur(function(){ //#q1 is the ID for the input field.
var d2 = new Date($('#q1').val());
var inputDate = returnDate(d2); // convert input date in dd/mm/yyyy format
if(inputDate > fixedDate){ // compare two dates
console.log('the input is bigger than the defined');
}else{
console.log('the defined is bigger than the input ');
}
});
});
// Write a general function to convert date in dd/mm/yyyy format
function returnDate(date){
var day=date.getDate();
var month=date.getMonth();
month=month+1;
if(day<10){
day='0'+day;
}
if(month<10){
month='0'+month;
}
var someday=day+ '/' + month + '/' + date.getFullYear();
return someday;
}
JSFIDDLE
EDIT 1
Use ternary operator instead of if-else
inputDate > fixedDate? (console.log("the input is bigger than the defined")):(console.log("the defined is bigger than the input"))
with ternary operator