In IE date is retrieved as NaN [duplicate] - javascript

I'm trying to build a little calendar in JavaScript. I have my dates working great in Firefox and Chrome, but in IE the date functions are returning NaN.
Here is the function :
function buildWeek(dateText){
var headerDates='';
var newDate = new Date(dateText);
for(var d=0;d<7;d++){
headerDates += '<th>' + newDate + '</th>';
newDate.setDate(newDate.getDate()+1);
}
jQuery('div#headerDates').html('<table><tr>'+headerDates+'</tr></table>');
}
dateText is the Monday of the current week which is actually set in php in the format of 'm, d, Y', e.g. "02, 01, 2010".

From a mysql datetime/timestamp format:
var dateStr="2011-08-03 09:15:11"; //returned from mysql timestamp/datetime field
var a=dateStr.split(" ");
var d=a[0].split("-");
var t=a[1].split(":");
var date = new Date(d[0],(d[1]-1),d[2],t[0],t[1],t[2]);
I hope is useful for someone.
Works in IE FF Chrome

The Date constructor accepts any value. If the primitive [[value]] of the argument is number, then the Date that is created has that value. If primitive [[value]] is String, then the specification only guarantees that the Date constructor and the parse method are capable of parsing the result of Date.prototype.toString and Date.prototype.toUTCString()
A reliable way to set a Date is to construct one and use the setFullYear and setTime methods.
An example of that appears here:
http://jibbering.com/faq/#parseDate
ECMA-262 r3 does not define any date formats. Passing string values to the Date constructor or Date.parse has implementation-dependent outcome. It is best avoided.
Edit:
The entry from comp.lang.javascript FAQ is:
An Extended ISO 8601 local date format YYYY-MM-DD can be parsed to a Date with the following:-
/**Parses string formatted as YYYY-MM-DD to a Date object.
* If the supplied string does not match the format, an
* invalid Date (value NaN) is returned.
* #param {string} dateStringInRange format YYYY-MM-DD, with year in
* range of 0000-9999, inclusive.
* #return {Date} Date object representing the string.
*/
function parseISO8601(dateStringInRange) {
var isoExp = /^\s*(\d{4})-(\d\d)-(\d\d)\s*$/,
date = new Date(NaN), month,
parts = isoExp.exec(dateStringInRange);
if(parts) {
month = +parts[2];
date.setFullYear(parts[1], month - 1, parts[3]);
if(month != date.getMonth() + 1) {
date.setTime(NaN);
}
}
return date;
}

Don't use "new Date()", because it takes the input date string as local time:
new Date('11/08/2010').getTime()-new Date('11/07/2010').getTime(); //90000000
new Date('11/07/2010').getTime()-new Date('11/06/2010').getTime(); //86400000
we should use "NewDate()", it takes the input as GMT time:
function NewDate(str)
{str=str.split('-');
var date=new Date();
date.setUTCFullYear(str[0], str[1]-1, str[2]);
date.setUTCHours(0, 0, 0, 0);
return date;
}
NewDate('2010-11-07').toGMTString();
NewDate('2010-11-08').toGMTString();

Here's another approach that adds a method to the Date object
usage: var d = (new Date()).parseISO8601("1971-12-15");
/**
* Parses the ISO 8601 formated date into a date object, ISO 8601 is YYYY-MM-DD
*
* #param {String} date the date as a string eg 1971-12-15
* #returns {Date} Date object representing the date of the supplied string
*/
Date.prototype.parseISO8601 = function(date){
var matches = date.match(/^\s*(\d{4})-(\d{2})-(\d{2})\s*$/);
if(matches){
this.setFullYear(parseInt(matches[1]));
this.setMonth(parseInt(matches[2]) - 1);
this.setDate(parseInt(matches[3]));
}
return this;
};

I always store my date in UTC time.
This is my own function made from the different functions I found in this page.
It takes a STRING as a mysql DATETIME format (example : 2013-06-15 15:21:41). The checking with the regex is optional. You can delete this part to improve performance.
This function return a timestamp.
The DATETIME is considered as a UTC date.
Be carefull : If you expect a local datetime, this function is not for you.
function datetimeToTimestamp(datetime)
{
var regDatetime = /^[0-9]{4}-(?:[0]?[0-9]{1}|10|11|12)-(?:[012]?[0-9]{1}|30|31)(?: (?:[01]?[0-9]{1}|20|21|22|23)(?::[0-5]?[0-9]{1})?(?::[0-5]?[0-9]{1})?)?$/;
if(regDatetime.test(datetime) === false)
throw("Wrong format for the param. `Y-m-d H:i:s` expected.");
var a=datetime.split(" ");
var d=a[0].split("-");
var t=a[1].split(":");
var date = new Date();
date.setUTCFullYear(d[0],(d[1]-1),d[2]);
date.setUTCHours(t[0],t[1],t[2], 0);
return date.getTime();
}

Here's a code snippet that fixes that behavior of IE
(v['date'] is a comma separated date-string, e.g. "2010,4,1"):
if($.browser.msie){
$.lst = v['date'].split(',');
$.tmp = new Date(parseInt($.lst[0]),parseInt($.lst[1])-1,parseInt($.lst[2]));
} else {
$.tmp = new Date(v['date']);
}
The previous approach didn't consider that JS Date month is ZERO based...
Sorry for not explaining too much, I'm at work and just thought this might help.

Here's my approach:
var parseDate = function(dateArg) {
var dateValues = dateArg.split('-');
var date = new Date(dateValues[0],dateValues[1],dateValues[2]);
return date.format("m/d/Y");
}
replace ('-') with the delimeter you're using.

Send the date text and format in which you are sending the datetext in the below method. It will parse and return as date and this is independent of browser.
function cal_parse_internal(val, format) {
val = val + "";
format = format + "";
var i_val = 0;
var i_format = 0;
var x, y;
var now = new Date(dbSysCurrentDate);
var year = now.getYear();
var month = now.getMonth() + 1;
var date = now.getDate();
while (i_format < format.length) {
// Get next token from format string
var c = format.charAt(i_format);
var token = "";
while ((format.charAt(i_format) == c) && (i_format < format.length)) {
token += format.charAt(i_format++);
}
// Extract contents of value based on format token
if (token == "yyyy" || token == "yy" || token == "y") {
if (token == "yyyy") { x = 4; y = 4; }
if (token == "yy") { x = 2; y = 2; }
if (token == "y") { x = 2; y = 4; }
year = _getInt(val, i_val, x, y);
if (year == null) { return 0; }
i_val += year.length;
if (year.length == 2) {
if (year > 70) {
year = 1900 + (year - 0);
} else {
year = 2000 + (year - 0);
}
}
} else if (token == "MMMM") {
month = 0;
for (var i = 0; i < MONTHS_LONG.length; i++) {
var month_name = MONTHS_LONG[i];
if (val.substring(i_val, i_val + month_name.length) == month_name) {
month = i + 1;
i_val += month_name.length;
break;
}
}
if (month < 1 || month > 12) { return 0; }
} else if (token == "MMM") {
month = 0;
for (var i = 0; i < MONTHS_SHORT.length; i++) {
var month_name = MONTHS_SHORT[i];
if (val.substring(i_val, i_val + month_name.length) == month_name) {
month = i + 1;
i_val += month_name.length;
break;
}
}
if (month < 1 || month > 12) { return 0; }
} else if (token == "MM" || token == "M") {
month = _getInt(val, i_val, token.length, 2);
if (month == null || month < 1 || month > 12) { return 0; }
i_val += month.length;
} else if (token == "dd" || token == "d") {
date = _getInt(val, i_val, token.length, 2);
if (date == null || date < 1 || date > 31) { return 0; }
i_val += date.length;
} else {
if (val.substring(i_val, i_val+token.length) != token) {return 0;}
else {i_val += token.length;}
}
}
// If there are any trailing characters left in the value, it doesn't match
if (i_val != val.length) { return 0; }
// Is date valid for month?
if (month == 2) {
// Check for leap year
if ((year%4 == 0 && year%100 != 0) || (year%400 == 0)) { // leap year
if (date > 29) { return false; }
} else {
if (date > 28) { return false; }
}
}
if (month == 4 || month == 6 || month == 9 || month == 11) {
if (date > 30) { return false; }
}
return new Date(year, month - 1, date);
}

The Date constructor in JavaScript needs a string in one of the date formats supported by the parse() method.
Apparently, the format you are specifying isn't supported in IE, so you'll need to either change the PHP code, or parse the string manually in JavaScript.

You can use the following code to parse ISO8601 date string:
function parseISO8601(d) {
var timestamp = d;
if (typeof (d) !== 'number') {
timestamp = Date.parse(d);
}
return new Date(timestamp);
};

Try out using getDate feature of datepicker.
$.datepicker.formatDate('yy-mm-dd',new Date(pField.datepicker("getDate")));

I tried all the above solution but nothing worked for me.
I did some brainstorming and found this and worked fine in IE11 as well.
value="2020-08-10 05:22:44.0";
var date=new Date(value.replace(" ","T")).$format("d/m/yy h:i:s");
console.log(date);
if $format is not working for you use format only.

Related

validate a date in dd/mm/yyyy format

I am trying to validate a date with regex but its failing, i am trying to use it to write it in input manually or select from a calendar on the side
<input type="text" name="FromDate" value="28/8/2022" id="Strtcalfield1" REQUIRED="yes" VALIDATE="date" MESSAGE="Please enter date (dd/MM/yyyy)." pattern="/^(\s{0,})(\d{2}\/\d{2}\/\d{4})(,\d{2}\/\d{2}\/\d{4}){1,}(\s){0,}$" oninvalid="this.setCustomValidity('Please enter date (dd/mm/yyyy).')" oninput="this.setCustomValidity('')"/>
and that is throwing an error
value is coming from backend, but when i choose rom calendar, it keeps on giving me an error
please enter date as dd/mm/yyyy as i see the date is correctly entered
You could validate the string with a JavaScript function instead of the regex pattern to ensure that it is a valid date. The following function parses the dd/mm/yyyy string pattern and ensures the day part is in the correct range for the parsed month and year values.
function validateDateString(dateString) {
// regex for date string format: dd/mm/yyyy
const dateFormatRegex = /^(0?[1-9]|[1-2][0-9]|3[01])[\/](0?[1-9]|1[0-2])[\/]\d{4}$/;
let isValidDate = false;
if (dateString.match(dateFormatRegex)) {
const dateParts = dateString.split('/');
if (dateParts.length == 3) {
const day = parseInt(dateParts[0]);
const month = parseInt(dateParts[1]);
const year = parseInt(dateParts[2]);
// valid month range is 1 - 12
if (month < 1 || month > 12) {
return false;
}
// validate days in month
const daysInMonth = [31,28,31,30,31,30,31,31,30,31,30,31];
let monthLength = daysInMonth[month-1];
if ((month == 2) && ((!(year%4) && year%100) || !(year%400))) {
monthLength = 29;
}
if (day < 1 || day > monthLength) {
return false;
}
// checks have passed
isValidDate = true;
}
}
return isValidDate;
}
EDIT: The following modifications will allow the code to handle the date format of the locale used in the browser.
The getLocaleDateFormat function determines the locale date format by generating a unique date and identifying the position of each element in the locale string. The date separator character is also identified and the information is returned in a single object with keys: day, month, year and sep.
function getLocaleDateFormat() {
const dummyDate = new Date(1999,11,30).toLocaleDateString().replace(/1999/,"yyyy").replace(/30/,"dd").replace(/12/,"mm");
const findDateSegmentIndex = (pos) => {
let index = -1;
if (pos == 0) {
index = 0;
}
else if ((pos > 0) & (pos < 6)) {
index = 1;
}
else if ((pos > 5) & (pos < 10)) {
index = 2;
}
return index;
};
const localeInfo = {
"day": findDateSegmentIndex(dummyDate.search("dd")),
"month": findDateSegmentIndex(dummyDate.search("mm")),
"year": findDateSegmentIndex(dummyDate.search("yyyy")),
"sep": dummyDate[dummyDate.search(/\W/)]
};
return localeInfo;
}
The getDateStringFormat function uses the information in the object returned by getLocaleDateFormat() to assemble a string to create the regular expression which will match the locale date format. The object returned by the function includes the regular expression string in the regex key.
function getDateStringFormat() {
const dateLocale = getLocaleDateFormat();
const regexStringsObject = {
"day": '(0?[1-9]|[1-2][0-9]|3[01])',
"month": '(0?[1-9]|1[0-2])',
"year": '\\d{4}'
}
let regexElements = ['', '', ''];
regexElements[ dateLocale["day"] ] = regexStringsObject["day"];
regexElements[ dateLocale["month"] ] = regexStringsObject["month"];
regexElements[ dateLocale["year"] ] = regexStringsObject["year"];
const dateStringFormat = { ...dateLocale,
"regex": `^${regexElements[0]}[.\\-\\/]${regexElements[1]}[.\\-\\/]${regexElements[2]}$`
};
return dateStringFormat;
}
The updated validateDateString function uses the regex string in the object returned by getDateStringFormat() to parse the provided dateString. There are three different separators (-, ., /) handled. The locale date format information as determined in the getLocaleDateFormat function is used to validate the respective part of the date string.
function validateDateString(dateString) {
const dateFormat = getDateStringFormat();
let result = false;
const regex = new RegExp(dateFormat.regex);
if (dateString.match(regex)) {
const dateParts = dateString.split(/[.\-\/]/);
if (dateParts.length == 3) {
const day = parseInt(dateParts[dateFormat.day]);
const month = parseInt(dateParts[dateFormat.month]);
const year = parseInt(dateParts[dateFormat.year]);
// valid month range is 1 - 12
if (month < 1 || month > 12) {
return false;
}
// validate days in month
const daysInMonth = [31,28,31,30,31,30,31,31,30,31,30,31];
let monthLength = daysInMonth[month-1];
if ((month == 2) && ((!(year%4) && year%100) || !(year%400))) {
monthLength = 29;
}
if (day < 1 || day > monthLength) {
return false;
}
// checks have passed
result = true;
}
}
return result;
}

check whether the date entered by the user is current date or the future date

I was browsing through the net to find a javascript function
which can check whether the date entered by the user is current date or the future date but i didn't found a suitable answer so i made it myself.Wondering If this can be achieved by one line code.
function isfutureDate(value)
{
var now = new Date;
var target = new Date(value);
if (target.getFullYear() > now.getFullYear())
{
return true;
}
else if(target.getFullYear() == now.getFullYear())
{
if (target.getMonth() > now.getMonth()) {
return true;
}
else if(target.getMonth() == now.getMonth())
{
if (target.getDate() >= now.getDate()) {
return true;
}
else
{
return false
}
}
}
else{
return false;
}
}
You can compare two dates as if they were Integers:
var now = new Date();
if (before < now) {
// selected date is in the past
}
Just both of them must be Date.
First search in google leads to this: Check if date is in the past Javascript
However, if you love programming, here's a tip:
A date formatted like YYYY-MM-DD could be something like 28-12-2013.
And if we reverse the date, it is 2013-12-28.
We remove the colons, and we get 20131228.
We set an other date: 2013-11-27 which finally is 20131127.
We can perform a simple operation: 20131228 - 20131127
Enjoy.
here's a version that only compares the date and excludes the time.
Typescript
const inFuture = (date: Date) => {
return date.setHours(0,0,0,0) > new Date().setHours(0,0,0,0)
};
ES6
const inFuture = (date) => {
return date.setHours(0,0,0,0) > new Date().setHours(0,0,0,0)
};
try out this
function isFutureDate(idate){
var today = new Date().getTime(),
idate = idate.split("/");
idate = new Date(idate[2], idate[1] - 1, idate[0]).getTime();
return (today - idate) < 0 ? true : false;
}
Demo
console.log(isFutureDate("02/03/2016")); // true
console.log(isFutureDate("01/01/2016")); // false
ES6 version with tolerable future option.
I made this little function that allows for some wiggle room (incase data coming in is from a slightly fast clock for example).
It takes a Date object and toleranceMillis which is the number of seconds into the future that is acceptable (defaults to 0).
const isDistantFuture = (date, toleranceMillis = 0) => {
// number of milliseconds tolerance (i.e. 60000 == one minute)
return date.getTime() > Date.now() + toleranceMillis
}
try this
function IsFutureDate(dateVal) {
var Currentdate = new Date();
dateVal= dateVal.split("/");
var year = Currentdate.getFullYear();
if (year < dateVal[2]) {
return false;//future date
}
else {
return true; //past date
}
}
In my case, I used DD-MM-YYYY format dates to compare and it gives an error since the behaviour of "DD-MM-YYYY" is undefined. So I convert it to a compatible format and compare it. And also if you need to compare only the dates and not time, you need to set time parameters to zero.
var inputDateVal = "14-06-2021";
if (inputDateVal != null && inputDateVal != '') {
var dateArr = inputDateVal.split("-");
var inputDate = new Date('"' + dateArr[2] + "-" + dateArr[1] + "-" + dateArr[0] + '"').setHours(0, 0, 0, 0);
var toDay = new Date().setHours(0, 0, 0, 0);
if(inputDate > toDay){
console.log("Date is a future date");
}else if(inputDate== toDay){
console.log("Date is equal to today");
}else{
console.log("Date is a past date");
}
}
You can use moment.js library
let dateToBeCompared = "10/24/2021"; // "DD/MM/YYYY" format
// For past dates
moment(dateToBeCompared, "DD/MM/YYYY").isBefore(moment(new Date(), "DD/MM/YYYY"),
'day')
// For same dates
moment(dateToBeCompared, "DD/MM/YYYY").isSame(moment(new Date(), "DD/MM/YYYY"),
'day')
// For future dates
moment(dateToBeCompared, "DD/MM/YYYY").isAfter(moment(new Date(), "DD/MM/YYYY"),
'day');
There are other functions like also like isSameOrAfter() and isSameOrBefore()
Have a look at here

Incorporate leading zero in my date validation

Here is my current date validation function:
isValidDate = function(day,month,year) {
var dteDate;
dteDate=new Date(year,month,day);
return ((day.toString()===dteDate.getDate().toString()) && (month.toString()===dteDate.getMonth().toString()) && (year.toString()===dteDate.getFullYear().toString()));
}
Then later I check the fields:
checkFields = function() {
var iDate = $("inspect_date").value;
if(iDate.length > 0) {
var a = iDate.split("/");
if(isValidDate(a[0],a[1]-1,a[2]) == false){
alert("You have entered an invalid date. Please amend!");
return false;
}
So at the moment it doesn't accept dates in the format dd/mm/yyy which is what I want - the function doesn't like the leading zero.
I tried to fix it in this way:
isValidDate = function(day,month,year) {
var dteDate;
dteDate=new Date(year,month,day);
var day = dteDate.getDate();
var month = dteDate.getMonth() + 1;
var year = dteDate.getFullYear();
var formatted =
(day < 10 ? "0" : "") + day + "/" +
(month < 10 ? "0" : "") + month + "/" +
year;
return ((day.toString()===dteDate.getDate().toString()) && (month.toString()===dteDate.getMonth().toString()) && (year.toString()===dteDate.getFullYear().toString()));
}
But now my 'return' part is containing the wrong values when it does the comparisons.
Can anyone help?
For the example date "02/04/2012" the first variation of your function passes "02", 3, "2012" as the arguments. Your function then tries to compare "02" with "2" which is obviously "not equal".
You should compare numbers as numbers. Unary + operator is a shortcut to convert a string to a number (+"01" yields 1; you can use parseInt as well):
return
+day === dteDate.getDate() &&
+month === dteDate.getMonth() &&
+year === dteDate.getFullYear();
Here is another way to validate dates using RegRx and JavaScript Date object.

Javascript - Regex to validate date format [duplicate]

This question already has answers here:
Javascript date regex DD/MM/YYYY
(13 answers)
Closed 6 years ago.
Is there any way to have a regex in JavaScript that validates dates of multiple formats, like: DD-MM-YYYY or DD.MM.YYYY or DD/MM/YYYY etc? I need all these in one regex and I'm not really good with it. So far I've come up with this: var dateReg = /^\d{2}-\d{2}-\d{4}$/; for DD-MM-YYYY. I only need to validate the date format, not the date itself.
You could use a character class ([./-]) so that the seperators can be any of the defined characters
var dateReg = /^\d{2}[./-]\d{2}[./-]\d{4}$/
Or better still, match the character class for the first seperator, then capture that as a group ([./-]) and use a reference to the captured group \1 to match the second seperator, which will ensure that both seperators are the same:
var dateReg = /^\d{2}([./-])\d{2}\1\d{4}$/
"22-03-1981".match(dateReg) // matches
"22.03-1981".match(dateReg) // does not match
"22.03.1981".match(dateReg) // matches
Format, days, months and year:
var regex = /^(0[1-9]|[12][0-9]|3[01])[- /.](0[1-9]|1[012])[- /.](19|20)\d\d$/;
The suggested regex will not validate the date, only the pattern.
So 99.99.9999 will pass the regex.
You later specified that you only need to validate the pattern but I still think it is more useful to create a date object
const isDDMMYYYY = str => {
let [dd, mm, yyyy] = str.split(/[\.\-\/]/); // change to suit your locale
dd = +dd; // cast to number
yyyy = +yyyy; // cast to number
let mm0 = mm - 1, // js months are 0 based
date = new Date(yyyy, mm0, dd, 15, 0, 0, 0); // normalise
return mm0 === date.getMonth() && dd === date.getDate() && yyyy === date.getFullYear();
};
const dates = [
"13-01-2023",
"13.01.2023",
"13/01/2023",
"08-08-1991",
"29/02/2011"
];
dates.forEach(date => console.log(date, ':', isDDMMYYYY(date)));
You can use regular multiple expressions with the use of OR (|) operator.
function validateDate(date){
var regex=new RegExp("([0-9]{4}[-](0[1-9]|1[0-2])[-]([0-2]{1}[0-9]{1}|3[0-1]{1})|([0-2]{1}[0-9]{1}|3[0-1]{1})[-](0[1-9]|1[0-2])[-][0-9]{4})");
var dateOk=regex.test(date);
if(dateOk){
alert("Ok");
}else{
alert("not Ok");
}
}
Above function can validate YYYY-MM-DD, DD-MM-YYYY date formats. You can simply extend the regular expression to validate any date format. Assume you want to validate YYYY/MM/DD, just replace "[-]" with "[-|/]". This expression can validate dates to 31, months to 12. But leap years and months ends with 30 days are not validated.
Make use of brackets /^\d{2}[.-/]\d{2}[.-/]\d{4}$/
http://download.oracle.com/javase/tutorial/essential/regex/char_classes.html
Please find in the below code which enables to perform the date validation for any of the supplied format or based on user locale to validate start/from and end/to dates. There could be some better approaches but have come up with this. Have tested it for the formats like: MM/dd/yyyy, dd/MM/yyyy, yyyy-MM-dd, yyyy.MM.dd, yyyy/MM/dd and dd-MM-yyyy.
Note supplied date format and date string go hand in hand.
<script type="text/javascript">
function validate(format) {
if(isAfterCurrentDate(document.getElementById('start').value, format)) {
alert('Date is after the current date.');
} else {
alert('Date is not after the current date.');
}
if(isBeforeCurrentDate(document.getElementById('start').value, format)) {
alert('Date is before current date.');
} else {
alert('Date is not before current date.');
}
if(isCurrentDate(document.getElementById('start').value, format)) {
alert('Date is current date.');
} else {
alert('Date is not a current date.');
}
if (isBefore(document.getElementById('start').value, document.getElementById('end').value, format)) {
alert('Start/Effective Date cannot be greater than End/Expiration Date');
} else {
alert('Valid dates...');
}
if (isAfter(document.getElementById('start').value, document.getElementById('end').value, format)) {
alert('End/Expiration Date cannot be less than Start/Effective Date');
} else {
alert('Valid dates...');
}
if (isEquals(document.getElementById('start').value, document.getElementById('end').value, format)) {
alert('Dates are equals...');
} else {
alert('Dates are not equals...');
}
if (isDate(document.getElementById('start').value, format)) {
alert('Is valid date...');
} else {
alert('Is invalid date...');
}
}
/**
* This method gets the year index from the supplied format
*/
function getYearIndex(format) {
var tokens = splitDateFormat(format);
if (tokens[0] === 'YYYY'
|| tokens[0] === 'yyyy') {
return 0;
} else if (tokens[1]=== 'YYYY'
|| tokens[1] === 'yyyy') {
return 1;
} else if (tokens[2] === 'YYYY'
|| tokens[2] === 'yyyy') {
return 2;
}
// Returning the default value as -1
return -1;
}
/**
* This method returns the year string located at the supplied index
*/
function getYear(date, index) {
var tokens = splitDateFormat(date);
return tokens[index];
}
/**
* This method gets the month index from the supplied format
*/
function getMonthIndex(format) {
var tokens = splitDateFormat(format);
if (tokens[0] === 'MM'
|| tokens[0] === 'mm') {
return 0;
} else if (tokens[1] === 'MM'
|| tokens[1] === 'mm') {
return 1;
} else if (tokens[2] === 'MM'
|| tokens[2] === 'mm') {
return 2;
}
// Returning the default value as -1
return -1;
}
/**
* This method returns the month string located at the supplied index
*/
function getMonth(date, index) {
var tokens = splitDateFormat(date);
return tokens[index];
}
/**
* This method gets the date index from the supplied format
*/
function getDateIndex(format) {
var tokens = splitDateFormat(format);
if (tokens[0] === 'DD'
|| tokens[0] === 'dd') {
return 0;
} else if (tokens[1] === 'DD'
|| tokens[1] === 'dd') {
return 1;
} else if (tokens[2] === 'DD'
|| tokens[2] === 'dd') {
return 2;
}
// Returning the default value as -1
return -1;
}
/**
* This method returns the date string located at the supplied index
*/
function getDate(date, index) {
var tokens = splitDateFormat(date);
return tokens[index];
}
/**
* This method returns true if date1 is before date2 else return false
*/
function isBefore(date1, date2, format) {
// Validating if date1 date is greater than the date2 date
if (new Date(getYear(date1, getYearIndex(format)),
getMonth(date1, getMonthIndex(format)) - 1,
getDate(date1, getDateIndex(format))).getTime()
> new Date(getYear(date2, getYearIndex(format)),
getMonth(date2, getMonthIndex(format)) - 1,
getDate(date2, getDateIndex(format))).getTime()) {
return true;
}
return false;
}
/**
* This method returns true if date1 is after date2 else return false
*/
function isAfter(date1, date2, format) {
// Validating if date2 date is less than the date1 date
if (new Date(getYear(date2, getYearIndex(format)),
getMonth(date2, getMonthIndex(format)) - 1,
getDate(date2, getDateIndex(format))).getTime()
< new Date(getYear(date1, getYearIndex(format)),
getMonth(date1, getMonthIndex(format)) - 1,
getDate(date1, getDateIndex(format))).getTime()
) {
return true;
}
return false;
}
/**
* This method returns true if date1 is equals to date2 else return false
*/
function isEquals(date1, date2, format) {
// Validating if date1 date is equals to the date2 date
if (new Date(getYear(date1, getYearIndex(format)),
getMonth(date1, getMonthIndex(format)) - 1,
getDate(date1, getDateIndex(format))).getTime()
=== new Date(getYear(date2, getYearIndex(format)),
getMonth(date2, getMonthIndex(format)) - 1,
getDate(date2, getDateIndex(format))).getTime()) {
return true;
}
return false;
}
/**
* This method validates and returns true if the supplied date is
* equals to the current date.
*/
function isCurrentDate(date, format) {
// Validating if the supplied date is the current date
if (new Date(getYear(date, getYearIndex(format)),
getMonth(date, getMonthIndex(format)) - 1,
getDate(date, getDateIndex(format))).getTime()
=== new Date(new Date().getFullYear(),
new Date().getMonth(),
new Date().getDate()).getTime()) {
return true;
}
return false;
}
/**
* This method validates and returns true if the supplied date value
* is before the current date.
*/
function isBeforeCurrentDate(date, format) {
// Validating if the supplied date is before the current date
if (new Date(getYear(date, getYearIndex(format)),
getMonth(date, getMonthIndex(format)) - 1,
getDate(date, getDateIndex(format))).getTime()
< new Date(new Date().getFullYear(),
new Date().getMonth(),
new Date().getDate()).getTime()) {
return true;
}
return false;
}
/**
* This method validates and returns true if the supplied date value
* is after the current date.
*/
function isAfterCurrentDate(date, format) {
// Validating if the supplied date is before the current date
if (new Date(getYear(date, getYearIndex(format)),
getMonth(date, getMonthIndex(format)) - 1,
getDate(date, getDateIndex(format))).getTime()
> new Date(new Date().getFullYear(),
new Date().getMonth(),
new Date().getDate()).getTime()) {
return true;
}
return false;
}
/**
* This method splits the supplied date OR format based
* on non alpha numeric characters in the supplied string.
*/
function splitDateFormat(dateFormat) {
// Spliting the supplied string based on non characters
return dateFormat.split(/\W/);
}
/*
* This method validates if the supplied value is a valid date.
*/
function isDate(date, format) {
// Validating if the supplied date string is valid and not a NaN (Not a Number)
if (!isNaN(new Date(getYear(date, getYearIndex(format)),
getMonth(date, getMonthIndex(format)) - 1,
getDate(date, getDateIndex(format))))) {
return true;
}
return false;
}
Below is the HTML snippet
<input type="text" name="start" id="start" size="10" value="05/31/2016" />
<br/>
<input type="text" name="end" id="end" size="10" value="04/28/2016" />
<br/>
<input type="button" value="Submit" onclick="javascript:validate('MM/dd/yyyy');" />
Try this:
^\d\d[./-]\d\d[./-]\d\d\d\d$
Don't re-invent the wheel. Use a pre-built solution for parsing dates, like http://www.datejs.com/
#mplungjan, #eduard-luca
function isDate(str) {
var parms = str.split(/[\.\-\/]/);
var yyyy = parseInt(parms[2],10);
var mm = parseInt(parms[1],10);
var dd = parseInt(parms[0],10);
var date = new Date(yyyy,mm-1,dd,12,0,0,0);
return mm === (date.getMonth()+1) &&
dd === date.getDate() &&
yyyy === date.getFullYear();
}
new Date() uses local time, hour 00:00:00 will show the last day when we have "Summer Time" or "DST (Daylight Saving Time)" events.
Example:
new Date(2010,9,17)
Sat Oct 16 2010 23:00:00 GMT-0300 (BRT)
Another alternative is to use getUTCDate().
To make sure it will work, you need to validate it.
function mmIsDate(str) {
if (str == undefined) { return false; }
var parms = str.split(/[\.\-\/]/);
var yyyy = parseInt(parms[2], 10);
if (yyyy < 1900) { return false; }
var mm = parseInt(parms[1], 10);
if (mm < 1 || mm > 12) { return false; }
var dd = parseInt(parms[0], 10);
if (dd < 1 || dd > 31) { return false; }
var dateCheck = new Date(yyyy, mm - 1, dd);
return (dateCheck.getDate() === dd && (dateCheck.getMonth() === mm - 1) && dateCheck.getFullYear() === yyyy);
};
If you want to validate your date(YYYY-MM-DD) along with the comparison it will be use full for you...
function validateDate()
{
var newDate = new Date();
var presentDate = newDate.getDate();
var presentMonth = newDate.getMonth();
var presentYear = newDate.getFullYear();
var dateOfBirthVal = document.forms[0].dateOfBirth.value;
if (dateOfBirthVal == null)
return false;
var validatePattern = /^(\d{4})(\/|-)(\d{1,2})(\/|-)(\d{1,2})$/;
dateValues = dateOfBirthVal.match(validatePattern);
if (dateValues == null)
{
alert("Date of birth should be null and it should in the format of yyyy-mm-dd")
return false;
}
var birthYear = dateValues[1];
birthMonth = dateValues[3];
birthDate= dateValues[5];
if ((birthMonth < 1) || (birthMonth > 12))
{
alert("Invalid date")
return false;
}
else if ((birthDate < 1) || (birthDate> 31))
{
alert("Invalid date")
return false;
}
else if ((birthMonth==4 || birthMonth==6 || birthMonth==9 || birthMonth==11) && birthDate ==31)
{
alert("Invalid date")
return false;
}
else if (birthMonth == 2){
var isleap = (birthYear % 4 == 0 && (birthYear % 100 != 0 || birthYear % 400 == 0));
if (birthDate> 29 || (birthDate ==29 && !isleap))
{
alert("Invalid date")
return false;
}
}
else if((birthYear>presentYear)||(birthYear+70<presentYear))
{
alert("Invalid date")
return false;
}
else if(birthYear==presentYear)
{
if(birthMonth>presentMonth+1)
{
alert("Invalid date")
return false;
}
else if(birthMonth==presentMonth+1)
{
if(birthDate>presentDate)
{
alert("Invalid date")
return false;
}
}
}
return true;
}

Date constructor returns NaN in IE, but works in Firefox and Chrome

I'm trying to build a little calendar in JavaScript. I have my dates working great in Firefox and Chrome, but in IE the date functions are returning NaN.
Here is the function :
function buildWeek(dateText){
var headerDates='';
var newDate = new Date(dateText);
for(var d=0;d<7;d++){
headerDates += '<th>' + newDate + '</th>';
newDate.setDate(newDate.getDate()+1);
}
jQuery('div#headerDates').html('<table><tr>'+headerDates+'</tr></table>');
}
dateText is the Monday of the current week which is actually set in php in the format of 'm, d, Y', e.g. "02, 01, 2010".
From a mysql datetime/timestamp format:
var dateStr="2011-08-03 09:15:11"; //returned from mysql timestamp/datetime field
var a=dateStr.split(" ");
var d=a[0].split("-");
var t=a[1].split(":");
var date = new Date(d[0],(d[1]-1),d[2],t[0],t[1],t[2]);
I hope is useful for someone.
Works in IE FF Chrome
The Date constructor accepts any value. If the primitive [[value]] of the argument is number, then the Date that is created has that value. If primitive [[value]] is String, then the specification only guarantees that the Date constructor and the parse method are capable of parsing the result of Date.prototype.toString and Date.prototype.toUTCString()
A reliable way to set a Date is to construct one and use the setFullYear and setTime methods.
An example of that appears here:
http://jibbering.com/faq/#parseDate
ECMA-262 r3 does not define any date formats. Passing string values to the Date constructor or Date.parse has implementation-dependent outcome. It is best avoided.
Edit:
The entry from comp.lang.javascript FAQ is:
An Extended ISO 8601 local date format YYYY-MM-DD can be parsed to a Date with the following:-
/**Parses string formatted as YYYY-MM-DD to a Date object.
* If the supplied string does not match the format, an
* invalid Date (value NaN) is returned.
* #param {string} dateStringInRange format YYYY-MM-DD, with year in
* range of 0000-9999, inclusive.
* #return {Date} Date object representing the string.
*/
function parseISO8601(dateStringInRange) {
var isoExp = /^\s*(\d{4})-(\d\d)-(\d\d)\s*$/,
date = new Date(NaN), month,
parts = isoExp.exec(dateStringInRange);
if(parts) {
month = +parts[2];
date.setFullYear(parts[1], month - 1, parts[3]);
if(month != date.getMonth() + 1) {
date.setTime(NaN);
}
}
return date;
}
Don't use "new Date()", because it takes the input date string as local time:
new Date('11/08/2010').getTime()-new Date('11/07/2010').getTime(); //90000000
new Date('11/07/2010').getTime()-new Date('11/06/2010').getTime(); //86400000
we should use "NewDate()", it takes the input as GMT time:
function NewDate(str)
{str=str.split('-');
var date=new Date();
date.setUTCFullYear(str[0], str[1]-1, str[2]);
date.setUTCHours(0, 0, 0, 0);
return date;
}
NewDate('2010-11-07').toGMTString();
NewDate('2010-11-08').toGMTString();
Here's another approach that adds a method to the Date object
usage: var d = (new Date()).parseISO8601("1971-12-15");
/**
* Parses the ISO 8601 formated date into a date object, ISO 8601 is YYYY-MM-DD
*
* #param {String} date the date as a string eg 1971-12-15
* #returns {Date} Date object representing the date of the supplied string
*/
Date.prototype.parseISO8601 = function(date){
var matches = date.match(/^\s*(\d{4})-(\d{2})-(\d{2})\s*$/);
if(matches){
this.setFullYear(parseInt(matches[1]));
this.setMonth(parseInt(matches[2]) - 1);
this.setDate(parseInt(matches[3]));
}
return this;
};
I always store my date in UTC time.
This is my own function made from the different functions I found in this page.
It takes a STRING as a mysql DATETIME format (example : 2013-06-15 15:21:41). The checking with the regex is optional. You can delete this part to improve performance.
This function return a timestamp.
The DATETIME is considered as a UTC date.
Be carefull : If you expect a local datetime, this function is not for you.
function datetimeToTimestamp(datetime)
{
var regDatetime = /^[0-9]{4}-(?:[0]?[0-9]{1}|10|11|12)-(?:[012]?[0-9]{1}|30|31)(?: (?:[01]?[0-9]{1}|20|21|22|23)(?::[0-5]?[0-9]{1})?(?::[0-5]?[0-9]{1})?)?$/;
if(regDatetime.test(datetime) === false)
throw("Wrong format for the param. `Y-m-d H:i:s` expected.");
var a=datetime.split(" ");
var d=a[0].split("-");
var t=a[1].split(":");
var date = new Date();
date.setUTCFullYear(d[0],(d[1]-1),d[2]);
date.setUTCHours(t[0],t[1],t[2], 0);
return date.getTime();
}
Here's a code snippet that fixes that behavior of IE
(v['date'] is a comma separated date-string, e.g. "2010,4,1"):
if($.browser.msie){
$.lst = v['date'].split(',');
$.tmp = new Date(parseInt($.lst[0]),parseInt($.lst[1])-1,parseInt($.lst[2]));
} else {
$.tmp = new Date(v['date']);
}
The previous approach didn't consider that JS Date month is ZERO based...
Sorry for not explaining too much, I'm at work and just thought this might help.
Here's my approach:
var parseDate = function(dateArg) {
var dateValues = dateArg.split('-');
var date = new Date(dateValues[0],dateValues[1],dateValues[2]);
return date.format("m/d/Y");
}
replace ('-') with the delimeter you're using.
Send the date text and format in which you are sending the datetext in the below method. It will parse and return as date and this is independent of browser.
function cal_parse_internal(val, format) {
val = val + "";
format = format + "";
var i_val = 0;
var i_format = 0;
var x, y;
var now = new Date(dbSysCurrentDate);
var year = now.getYear();
var month = now.getMonth() + 1;
var date = now.getDate();
while (i_format < format.length) {
// Get next token from format string
var c = format.charAt(i_format);
var token = "";
while ((format.charAt(i_format) == c) && (i_format < format.length)) {
token += format.charAt(i_format++);
}
// Extract contents of value based on format token
if (token == "yyyy" || token == "yy" || token == "y") {
if (token == "yyyy") { x = 4; y = 4; }
if (token == "yy") { x = 2; y = 2; }
if (token == "y") { x = 2; y = 4; }
year = _getInt(val, i_val, x, y);
if (year == null) { return 0; }
i_val += year.length;
if (year.length == 2) {
if (year > 70) {
year = 1900 + (year - 0);
} else {
year = 2000 + (year - 0);
}
}
} else if (token == "MMMM") {
month = 0;
for (var i = 0; i < MONTHS_LONG.length; i++) {
var month_name = MONTHS_LONG[i];
if (val.substring(i_val, i_val + month_name.length) == month_name) {
month = i + 1;
i_val += month_name.length;
break;
}
}
if (month < 1 || month > 12) { return 0; }
} else if (token == "MMM") {
month = 0;
for (var i = 0; i < MONTHS_SHORT.length; i++) {
var month_name = MONTHS_SHORT[i];
if (val.substring(i_val, i_val + month_name.length) == month_name) {
month = i + 1;
i_val += month_name.length;
break;
}
}
if (month < 1 || month > 12) { return 0; }
} else if (token == "MM" || token == "M") {
month = _getInt(val, i_val, token.length, 2);
if (month == null || month < 1 || month > 12) { return 0; }
i_val += month.length;
} else if (token == "dd" || token == "d") {
date = _getInt(val, i_val, token.length, 2);
if (date == null || date < 1 || date > 31) { return 0; }
i_val += date.length;
} else {
if (val.substring(i_val, i_val+token.length) != token) {return 0;}
else {i_val += token.length;}
}
}
// If there are any trailing characters left in the value, it doesn't match
if (i_val != val.length) { return 0; }
// Is date valid for month?
if (month == 2) {
// Check for leap year
if ((year%4 == 0 && year%100 != 0) || (year%400 == 0)) { // leap year
if (date > 29) { return false; }
} else {
if (date > 28) { return false; }
}
}
if (month == 4 || month == 6 || month == 9 || month == 11) {
if (date > 30) { return false; }
}
return new Date(year, month - 1, date);
}
The Date constructor in JavaScript needs a string in one of the date formats supported by the parse() method.
Apparently, the format you are specifying isn't supported in IE, so you'll need to either change the PHP code, or parse the string manually in JavaScript.
You can use the following code to parse ISO8601 date string:
function parseISO8601(d) {
var timestamp = d;
if (typeof (d) !== 'number') {
timestamp = Date.parse(d);
}
return new Date(timestamp);
};
Try out using getDate feature of datepicker.
$.datepicker.formatDate('yy-mm-dd',new Date(pField.datepicker("getDate")));
I tried all the above solution but nothing worked for me.
I did some brainstorming and found this and worked fine in IE11 as well.
value="2020-08-10 05:22:44.0";
var date=new Date(value.replace(" ","T")).$format("d/m/yy h:i:s");
console.log(date);
if $format is not working for you use format only.

Categories