validate a date in dd/mm/yyyy format - javascript

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;
}

Related

Check if Date is in Range

I have a date range suppose 2000-01-01 to 2021-06-01. I want to check whether a particular month with a given year falls in this range or not (E.g., month = March and year = 2021) using JavaScript.
Create a reusable function isDateInRange that accepts your three date Strings arguments.
Than you can simply compare your Date Objects using the needed operands:
const isDateInRange = (date, from, to) => {
const d = new Date(date);
const f = new Date(from);
const t = new Date(to);
return (d >= f && d < t);
};
console.log(isDateInRange("2001-01-31", "2000-01-01", "2021-06-01")) // true
console.log(isDateInRange("2050-01-01", "2000-01-01", "2021-06-01")) // false
Here is a solution passing month and year (not a date) as you requested.
const lowerRange = new Date('2000-01-01');
const upperRange = new Date('2021-06-01');
// If month and year are numbers
const monthYearInRange = (year, month) => {
if (typeof month !== 'number') throw new Error('Month should be number');
if (typeof year !== 'number') throw new Error('Year should be number');
// We do this to make sure it is 2 chars.
const mth = month < 10 ? `0${month}` : month;
// Set it to first of the month
const checkVal = new Date(`${year}-${mth}-01`);
if (isNaN(checkVal)) throw new Error(`Year: ${year} and Month: ${month} are not valid.`);
return checkVal <= upperRange && checkVal >= lowerRange;
}
console.log(monthYearInRange(2000, 2)); // true
console.log(monthYearInRange(2030, 2)); // false
console.log(monthYearInRange(2021, 6)); // true
console.log(monthYearInRange(2021, 10)); // false
Just a note on this solution - because ultimately we convert the year/month into a date, when doing this we have to instantiate the date using the ISO format YYYY-MM-DD. If checkVal gets instantiated with a month that is a single character (1 instead of 01) it will still work in most cases - but you will get edge cases breaking because the Date() constructor will add timezone values to the date.
Update: Added NaN check - per #RobG
I tried the following approach and it worked:
function isBetween(n, a, b) {
return (n - a) * (n - b) <= 0
}
var startDate = '2021-03-15';
var endDate = '2021-06-01';
var checkFor = '2021-05-31';
D_1 = startDate.split("-");
D_2 = endDate.split("-");
D_3 = checkFor.split("-");
//console.log(D_1+" "+D_2+" "+D_3);
var startNumber = D_1[0]*100 + D_1[1];
var endNumber = D_2[0]*100 + D_2[1];
var checkNumber = D_3[0]*100 + D_3[1];
var check = isBetween(checkNumber, startNumber, endNumber);
console.log(check);

Javascript Calculating year diff error in date?

I am trying to understand the date in JavaScript. But I can't get it.
I create a function that takes two dates and returns a value based on the difference of dates.
Here is the whole code:
function checkDate(birth_date, download_date) {
let yearDiff = download_date.getFullYear() - birth_date.getFullYear();
console.log(yearDiff);
if (yearDiff > 5) return "Not Eligible";
if (yearDiff < 5) return "Eligible";
if (yearDiff == 5) {
// Eligible only if 5 years or low
// If diff is Exact 5 Years Check if Bday is on download date ?
// First Check Month
let monthDiff = download_date.getMonth() - birth_date.getMonth();
if (monthDiff >= 1) {
return "Not Eligible"
}
if (monthDiff <= -1) {
return "Eligible"
}
if (monthDiff = 0) {
// Check Day
let dateDiff = download_date.getDay() - birth_date.getDay();
if (dateDiff <= 0) {
return "Eligible"
} else {
return "Not Eligible"
}
}
}
}
let dob_string = "DOB: 14/09/2016";
let dl_string = "Download Date: 03/11/2020";
let dob = new Date(dob_string.substr(dob_string.indexOf("DOB:") + 4, 11).trim());
let dld = new Date(dl_string.substr(dl_string.indexOf("Download") + 14, 11).trim());
console.log(checkDate(dob,dld));
The is the date is not getting created it says Invalid Date.
I want to check if the DOB difference is 5 more or not.
The problem is the new Date constructor doesn't understand dd/mm/yyyy format and is implemented differently on different browsers. What you need to do is convert it into valid format.
One way is to split it and pass into the constructor like this:
let dob_string = "DOB: 14/09/2016";
let dl_string = "Download Date: 03/11/2020";
let dob = dob_string.substr(dob_string.indexOf("DOB:") + 4, 11).trim();
const splitDOB = dob.split('/')
const validDate = new Date(
parseInt(splitDOB[2], 10),
parseInt(splitDOB[1], 10) - 1,
parseInt(splitDOB[0], 10)
);
The - 1 in the second param is because month is 0-indexed. Then you can process with the logic of your own function.
But I highly recommend using 3rd party lib such as dayjs when working with date/time in JS
so i tested it and even the substrings creates invalid dates.
so i wrote you this:
function checkDate(birth_date, download_date) {
let yearDiff = download_date.getFullYear() - birth_date.getFullYear();
console.log(yearDiff);
if (yearDiff > 5) return "Not Eligible";
if (yearDiff < 5) return "Eligible";
if (yearDiff == 5) {
// Eligible only if 5 years or low
// If diff is Exact 5 Years Check if Bday is on download date ?
// First Check Month
let monthDiff = download_date.getMonth() - birth_date.getMonth();
if (monthDiff >= 1) {
return "Not Eligible"
}
if (monthDiff <= -1) {
return "Eligible"
}
if (monthDiff == 0) {
// Check Day
let dateDiff = download_date.getDay() - birth_date.getDay();
if (dateDiff <= 0) {
return "Eligible"
} else {
return "Not Eligible"
}
}
}
}
let dob_string = "DOB: 14/09/2016";
let dl_string = "Download Date: 03/11/2020";
function filterDate(str) {
const match = str.match(/(\d{1,2}).(\d{1,2}).(\d{4})/);
let year = match[3];
let month = match[2];
let day = match[1];
if (isNaN(year) || isNaN(month) || isNaN(day)) {
throw new Error("no valid date");
}
// fix strings to numbers;
year = +year;
month = +month;
day = +day;
// months begins on 0
month = month - 1;
return new Date(year, month, day);
}
console.log(checkDate(filterDate(dob_string),filterDate(dl_string)));

Javascript date validator for multiple date patterns

With help from stackoverflow I made a .js file with two methods that check if the date entered is valid. It is working fine, but only if the date is entered with dashes - 12/12/2019. What approach can I take in my isValidDate method to make it work with multiple date patterns like - 12.12.2020 12-12-2020 etc. The only idea I have is to check somehow first what is the pattern and then create a separate case to split the date string by different characters, but it will look pretty ugly.
function isValidDate(dateString) {
var validDate = true;
// First check for the pattern
if (!/^\d{1,2}\/\d{1,2}\/\d{4}$/.test(dateString)) {
return false;
}
// Parse the date parts to integers
var parts = dateString.split("/");
var day = parseInt(parts[0], 10);
var month = parseInt(parts[1], 10);
var year = parseInt(parts[2], 10);
if(isNaN(day) || isNaN(month) || isNaN(year)){
return false;
}
// Check the ranges of month and year
if (year < 1000 || year > 3000 || month < 1 || month > 12) {
return false;
}
var monthLength = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
// Adjust for leap years
if (year % 400 == 0 || (year % 100 != 0 && year % 4 == 0)) {
monthLength[1] = 29;
}
// Check the range of the day
if (!(day > 0 && day <= monthLength[month - 1])) {
return false;
}
return true;
};
/**
* Function which executes each time the input loses focus (onblur)
*/
function validateDate() {
// Get a reference to the container
var container = document.querySelector('.date');
// Clear stale error/success messages
container.className = container.className.replace('success', '');
container.className = container.className.replace('error', '');
// Get current value of input
var dateString = document.getElementById("Start-date").value;
// Test if the string is a valid date
var isValid = isValidDate(dateString);
// Update classess of container to show success/error
if (!isValid) {
container.className += ' error';
} else {
container.className += ' success';
}
}
I am calling the validateDate() function first
Please note I have not tested the regular expressions this is just an example of how to attack the probelm
// First check for the pattern var = dateChar
if (!/^\d{1,2}\/\d{1,2}\/\d{4}$/.test(dateString)) {
dateChar = '/';
}
if (!/^\d{1,2}\-\d{1,2}\-\d{4}$/.test(dateString)) {
dateChar = '-';
}
if (!dateChar) {
return false;
}
var parts = dateString.split(dateChar);
....

In IE date is retrieved as NaN [duplicate]

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.

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