0

month ago I was working on weather website, and finished it, I have 5 content card there and each card discribes each day of weather and on top of card I have included week day, when I make API request I get date format like that 6-21-2021, I try to align this date string, to make readable for new Date() in Javascript to pull correct number of week day from Javascript Method

this is what I do

const weekDays: string[] = ["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday",];

//this part is included in get request
const dateFormatAPI = (response.data.list[0].dt_txt).split("-") //6-21-2021 -> ["6", "21", "2021"]
const alignedDate: string = String([dateFormatAPI[1],dateFormatAPI[2],dateFormatAPI[0]]) //"21, 6, 2021"
.replace(",", "-")
.replace(",", "-") //Output: 21-6-2021

const date = new Date(alignedDate); //putting this format in Date Method

console.log(days[date.getDay()]) //and getting current number putting this as array index and get week day  

it outputs week day, But it only outputs on Windows computer, and on Android

when I let to my friened check my website on IOS, she got error instead of showing week day she was getting undefined

and I have question why happens like that? how can I fix it?

if you use IOS right now, you can check on your own this website Weather Website

callmenikk
  • 1,358
  • 2
  • 9
  • 24

1 Answers1

1

Parsing a string to create another string that is parsed by the built–in parser is not a good idea, see Why does Date.parse give incorrect results?

"21-6-2021" is not a format supported by ECMA-262 so parsing is implementation dependent and iOS treats it as an invalid date.

A library can help, but isn't necessary. To parse the string try:

let s = '6-21-2021';
// Split on non–digit character
let [m, d, y] = s.split(/\D/);
// Use the Date constructor
let date = new Date(y, m - 1, d);

console.log(date.toDateString());
console.log(date.getDay());
console.log(date.toLocaleString('default',{weekday:'long'}));
RobG
  • 142,382
  • 31
  • 172
  • 209