Related
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;
}
I am using Google Apps Script to check and re-format date data from some Google Sheets. But the problem is the result shows the times for the user who run the code. I want to show the date for any specific time zone. How is it possible?
Suppose, my input is checkDate('14/5/2022'); and it returns the date
object for that time zone instead of my time zone.
Here is my code:
/**
* This will return a JS Date object with a valid date input.
* Unless this will return a false status
*/
function checkDate(input) {
// const timeZone = SpreadsheetApp.getActive().getSpreadsheetTimeZone();
if (input instanceof Date && !isNaN(input)) {
// will execute if a valid date
return input;
} else {
// If not a valid date
const splitter = input.indexOf('/') === -1 ? '-' : '/';
const dateArr = input.split(splitter);
if(dateArr.length === 3) {
const year = dateArr[2].length === 2 ? '20' + dateArr[2] : dateArr[2];
const NewTime = new Date(Date.UTC(year, dateArr[1]-1, dateArr[0], 0, 0, 0));
return NewTime;
} else {
return false;
}
}
}
console.log(checkDate(new Date()));
console.log(checkDate('14/5/2022'));
Expected input
checkDate('14/5/2022') and timeZone = 'GMT+1;
Expected Output
2022-05-14T00:00:00.000 french time. Not the UTC time.
Is it possible?
Apps Script is JavaScript, and JavaScript Date objects are always in UTC.
When you return a Date object from a custom function, or directly write a Date object to a spreadsheet cell from another type of function, it is automatically converted to the timezone of the spreadsheet. To set the spreadsheet timezone, choose File > Settings > Time zone.
To write a date so that it appears to use another timezone, convert the Date to a text string for display with Utilities.formatDate(), like this:
const date = new Date();
const timezone = {
spreadsheet: SpreadsheetApp.getActive().getSpreadsheetTimeZone(),
paris: 'Europe/Paris',
};
console.log(Utilities.formatDate(date, timezone.spreadsheet, 'yyyy-MM-dd HH:mm, zzzz'));
console.log(Utilities.formatDate(date, timezone.paris, 'yyyy-MM-dd HH:mm, zzzz'));
2022-05-14T00:00:00.000 is string, so add this function
function myFormat(date) {
return date.getFullYear()
+ '-'
+ ((date.getMonth() + 1) < 10 ? '0' + (date.getMonth() + 1) : (date.getMonth() + 1))
+ '-'
+ (date.getDate() < 10 ? '0' + date.getDate() : date.getDate())
+ 'T00:00:00.000'
}
complete script
function checkDate(input) {
// const timeZone = SpreadsheetApp.getActive().getSpreadsheetTimeZone();
if (input instanceof Date && !isNaN(input)) {
// will execute if a valid date
return myFormat(input);
} else {
// If not a valid date
const splitter = input.indexOf('/') === -1 ? '-' : '/';
const dateArr = input.split(splitter);
if (dateArr.length === 3) {
const year = dateArr[2].length === 2 ? '20' + dateArr[2] : dateArr[2];
const NewTime = new Date(Date.UTC(year, dateArr[1] - 1, dateArr[0], 0, 0, 0));
return myFormat(NewTime);
} else {
return false;
}
}
}
function myFormat(date) {
return date.getFullYear()
+ '-'
+ ((date.getMonth() + 1) < 10 ? '0' + (date.getMonth() + 1) : (date.getMonth() + 1))
+ '-'
+ (date.getDate() < 10 ? '0' + date.getDate() : date.getDate())
+ 'T00:00:00.000'
}
function test() {
console.log(checkDate('14/05/2022'))
}
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.
This may sound like a dumb question, but is it possible to have a 0 at the start of a number check, and have it work?
This is what I have:
function checkCosts() {
var date = document.getElementsByName("date")[0].value;
var roomtype = document.getElementsByName("roomtype")[0].value;
var night = document.getElementsByName("night")[0].value;
var month = date.substring(0, 2);
var year = date.substring(8, 10);
var day = date.substring(4, 6);
var time = month.concat(year);
var fulldate = day.concat(time);
if (time >= 0415 && <= 0915) {
if (roomtype == "Classic") {
if (night == "3") {
document.getElementById("cost").innerHTML = "1,480";
}
}
}
}
However, when I run it in jslint.com I get the following errors:
Unexpected '4' after '0'.
if(time >= 0415 && <= 0915){
line 9 column 28Unexpected trailing space.
if(time >= 0415 && <= 0915){
What's there is just one of a few different statements, all the variables will be used.
It would be possible to convert the strings into ints, but I don't know how to do this/if it will work.
A leading 0 is not the way to use ints. You should take a look here.
Otherwise just use the alpabetical order using a string comparison.
There is just no need to add zeros in front of the number. If the first number identifies the level of the room just add it, where you need it.
Instead of concatenating month with year, Concatenate year with month, And then check.
You need to do some modification in your logic.
function checkCosts() {
var date = document.getElementsByName("date")[0].value;
var roomtype = document.getElementsByName("roomtype")[0].value;
var night = document.getElementsByName("night")[0].value;
var month = date.substring(0, 2);
var year = date.substring(8, 10);
var day = date.substring(4, 6);
var time = year.concat(month);//Concat year with month.
var fulldate = day.concat(time);
if (time >= 1504 && <= 1509) { //Year should be first
if (roomtype == "Classic") {
if (night == "3") {
document.getElementById("cost").innerHTML = "1,480";
}
}
}
}
If you are trying to convert date to number and want to compare, use year first then month.
from this:
var time = month.concat(year);
I deduce "time" is a string.
then you should put quotes on 0415
strings are compared using alphabetical order (I hope you don't need globalization in this comparison) :
"04".concat("16") >= "0415"
-> true
"04".concat("14") >= "0415"
-> false
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.