I have the following snippet that works on my pc desktop. It works there but not on my iphone.
function dateFormat(date,type){
let dayOfWeek = ['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday'];
let month = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];
date.replaceAll("-","/");
date = new Date(date " EDT");
function daySuffix(d) {
if (d > 3 && d < 21) return d 'th';
switch (d % 10) {
case 1: return d "st";
case 2: return d "nd";
case 3: return d "rd";
default: return d "th";
}
}
let day = daySuffix(date.getDate());
let string = "";
switch(type){
case 'ld': string = dayOfWeek[date.getDay()] ", " month[date.getMonth()] " " day;break;
case 'sd': string = month[date.getMonth()] " " day;break;
default: string = "wrong type, ld or sd only";
}
console.log(string,'string');
return string;
}
console.log(dateFormat("2022-05-06","ld"))
CodePudding user response:
the problem is just with this line:
date.replaceAll("-","/");
it needs to be:
date = date.replaceAll("-","/");
function dateFormat(date,type){
let dayOfWeek = ['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday'];
let month = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];
date = date.replaceAll("-","/");
date = new Date(date " EDT");
function daySuffix(d) {
if (d > 3 && d < 21) return d 'th';
switch (d % 10) {
case 1: return d "st";
case 2: return d "nd";
case 3: return d "rd";
default: return d "th";
}
}
let day = daySuffix(date.getDate());
let string = "";
switch(type){
case 'ld': string = dayOfWeek[date.getDay()] ", " month[date.getMonth()] " " day;break;
case 'sd': string = month[date.getMonth()] " " day;break;
default: string = "wrong type, ld or sd only";
}
console.log(string,'string');
return string;
}
console.log(dateFormat("2022-05-06","ld"))
CodePudding user response:
The problem is with timezone that is appended to date string EDT
. It is making incorrect date string "2022-05-06 EDT"
.
You may archive setting timezone by formatting date and parsing it back (still it has no impact on date only dates).
function dateFormat(date,type){
let dayOfWeek = ['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday'];
let month = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];
date = new Date(new Date(date).toLocaleString('en-US', {
timeZone: "America/Detroit"
}));
function daySuffix(d) {
if (d > 3 && d < 21) return d 'th';
switch (d % 10) {
case 1: return d "st";
case 2: return d "nd";
case 3: return d "rd";
default: return d "th";
}
}
let day = daySuffix(date.getDate());
let string = "";
switch(type){
case 'ld': string = dayOfWeek[date.getDay()] ", " month[date.getMonth()] " " day;break;
case 'sd': string = month[date.getMonth()] " " day;break;
default: string = "wrong type, ld or sd only";
}
console.log(string,'string');
return string;
}
console.log(dateFormat("2022-05-06","ld"))