Related
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.
var now = new Date('18/10/2016 10:31:22PM');
var time = now.toLocaleTimeString();
alert(time);
this function give an output invalid date. I want to convert this "18/10/2016 22:31:22" format. give me an appropriate example as a solution.
this function should work for your date format
function convertDate(date_string){
var d = date_string.trim();
d = d.split(" ");
v = d[1].split(":")[0];
v = d[1].indexOf("PM")>-1 ? +v+12 : v;
d[1] = d[1].replace(d[1].split(":")[0],v);
d = d.join(" ").replace("PM","").replace("AM","");
return d;
}
console.log(convertDate("18/10/2016 10:31:22PM"));
console.log(convertDate("01/10/2016 09:31:22PM"));
console.log(convertDate("06/10/2016 2:31:22AM"));
console.log(convertDate("07/10/2016 7:31:22AM"));
Without using a library, you will need to extract all the date tokens and send them into a new date object in the correct order. From there, you can create your own date formatting function.
var DATE_FORMAT = /(\d{1,2})\/(\d{1,2})\/(\d{4}) (\d{1,2}):(\d{2}):(\d{2})([AP]M)/;
var dateStr = '18/10/2016 10:31:22PM';
var now = parseDateString(dateStr, DATE_FORMAT, function(tokens) {
return [
parseInt(tokens[3], 10), // year
parseInt(tokens[2], 10) - 1, // month
parseInt(tokens[1], 10), // date
to24(parseInt(tokens[4], 10), tokens[7]), // hours, meridiem
parseInt(tokens[5], 10), // minutes
parseInt(tokens[6], 10), // seconds
0 // milliseconds
];
});
document.body.innerHTML = formateDate(now);
function parseDateString(dateStr, dateFormat, func) {
var tokens = dateStr.match(dateFormat);
var args = Array.prototype.concat.apply([null], func(tokens));
return new (Function.prototype.bind.apply(Date, args));
}
function formateDate(date, dateSeparator) {
return [
pad2(date.getDate()),
pad2(date.getMonth() + 1),
date.getFullYear()
].join(dateSeparator || '/') + ' ' + [
pad2(date.getHours()),
pad2(date.getMinutes()),
pad2(date.getSeconds())
].join(':');
}
function pad2(str) { return ('00' + str).substr(-2); }
function to24(hours, meridiem) {
switch (meridiem) {
case 'PM': if (hours < 12) return hours + 12;
case 'AM': if (hours === 12) return hours - 12;
default: return hours;
}
}
Of course, this can be done in moment with one line.
var dateStr = '18/10/2016 10:31:22PM';
var time = moment(dateStr, 'DD/MM/YYYY hh:mm:ssA').format('DD/MM/YYYY HH:mm:ss');
document.body.innerHTML = time;
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.15.1/moment.min.js"></script>
I'm using this angular filter in my application to take a time stamp and convert it into 'time ago' time such as '3 hours ago'. I found the filter as a github gist and forked it to make it do conversions from UTC to the end user's local time. Now I'm can figure out why it only seems to work in chrome (note: I don't know if the original ever worked outside of chrome either). Safari and Firefox output 'in a long time' for all the times available from my application which span from a few minutes ago to a couple weeks ago. Any ideas?
app.filter('timeago', function () {
//time: the time
//local: compared to what time? default: now
//raw: whether you want in a format of "5 minutes ago", or "5 minutes"
return function (time, local, raw) {
var timeZoneOffset = (new Date().getTimezoneOffset()) * 60000;
if (!time) return "never";
if (!local) {
(local = Date.now());
}
if (angular.isDate(time)) {
time = time.getTime();
} else if (typeof time === "string") {
// convert string time to milliseconds
time = new Date(time).getTime();
}
// convert UTC to local
time = time - timeZoneOffset;
if (angular.isDate(local)) {
local = local.getTime();
}else if (typeof local === "string") {
local = new Date(local).getTime();
}
if (typeof time !== 'number' || typeof local !== 'number') {
return;
}
var span = [],
MINUTE = 60,
HOUR = 3600,
DAY = 86400,
WEEK = 604800,
MONTH = 2629744,
YEAR = 31556926,
DECADE = 315569260;
var offset = Math.abs((local - time) / 1000);
if (offset <= MINUTE) span = [ '', raw ? 'now' : 'a minute' ];
else if (offset < (MINUTE * 60)) span = [ Math.round(Math.abs(offset / MINUTE)), 'min' ];
else if (offset < (HOUR * 24)) span = [ Math.round(Math.abs(offset / HOUR)), 'hr' ];
else if (offset < (DAY * 7)) span = [ Math.round(Math.abs(offset / DAY)), 'day' ];
else if (offset < (WEEK * 52)) span = [ Math.round(Math.abs(offset / WEEK)), 'week' ];
else if (offset < (YEAR * 10)) span = [ Math.round(Math.abs(offset / YEAR)), 'year' ];
else if (offset < (DECADE * 100)) span = [ Math.round(Math.abs(offset / DECADE)), 'decade' ];
else span = [ '', 'a long time' ];
span[1] += (span[0] === 0 || span[0] > 1) ? 's' : '';
span = span.join(' ');
if (raw === true) {
return span;
}
return (time <= local) ? span + ' ago' : 'in ' + span;
};
});
EDIT:
Here is an condensed example of how i'm using it in html and the format that my api is returning date strings in. If other's are not having issues it could be related to how date strings are converted to millisecond time.
Time from within an angular controller
$scope.time = "2014-07-04 23:04:12";
From the html
<span>{{ time | timeago }}</span>
Display from firefox
'in a long time'
It appears that Date.parse might be implementation dependent. Based on this SO post and recommendation, I modified the custom parseDate function and verified that it works on IE, Chrome, and Firefox.
app.controller('ctrl', function($scope) {
// parse a date in yyyy-mm-dd format
function parseDate(input) {
var parts = input.split('-');
var timeBits = parts[2].split(' ');
var hms = timeBits[1].split(':');
// new Date(year, month [, day [, hours[, minutes[, seconds[, ms]]]]])
return new Date(parts[0], parts[1]-1, timeBits[0], hms[0], hms[1], hms[2]); // Note: months are 0-based
}
$scope.time = parseDate("2014-07-04 23:04:12");
alert($scope.time);
});
I was having the same issue. For me it was the date format with time zone that wasn't working.
"2014-07-04 23:04:12 GMT" This wasn't working
"2014/07/04 23:04:12 GMT" This worked
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.