2

I wrote a very basic JS function to create a clock. It uses a very basic replace method to change a "," to a "|" symbol. The desired output is "Thursday, Jan. 12, 2023 | 10:00:00 p.m."

const refreshTime = () => {
  let t = 0;

  const timeNow = (new Date).toLocaleString('en-CA', {
    timeZone: "America/Edmonton", year: "numeric", month: "short",
    weekday: "long", day: "numeric", hour12:true, hour: "numeric",  
    minute: "2-digit", second: "2-digit"
  }).replace(/,/g, match => ++t === 3 ? ' |' : match)

  const time = document.querySelector(".time")
  time.innerHTML = `${timeNow}`
}

refreshTime()
setInterval(refreshTime, 1000)
<h2 class="time">""<h2>

As you can see here on the deployed site, this clock works fine in the header section. But once you click on that same link on a phone, it displays as "Thursday, Jan 12, 2023 at 10:00:00 p.m."

I've tried with multiple mobile browsers and also tried deploying on vercel and it is giving me the same result. How can I make sure this displays as intended on mobile?

EDD
  • 2,070
  • 1
  • 10
  • 23
  • I don't know JS well, but couldn't you create a data string and a time string which you then concatenate with `|` as third string in between? And, do you have any idea what causes the `at`? – meaning-matters Jan 13 '23 at 07:15
  • 2
    The output of *toLocaleString* is implementation dependent. You **can't** expect exactly the same format to be produced by different implementations, or even different versions of an implementation. The solution is to use some other *reliable* method for formatting. PS the format I see on MacOS is "Friday, Jan 13, 2023 at 2:25:52 AM", so it's not just phone browsers. – RobG Jan 13 '23 at 09:23
  • Didn't know that Rob. Thanks for sharing that. I'll look into some other formatting method. – Learn to Code Jan 13 '23 at 17:26
  • Try th8is different replace: `(new Date).toLocaleString('en-CA', {timeZone: "America/Edmonton", year:"numeric", month:"short", weekday: "long", day:"numeric", hour12:true, hour: "numeric", minute:"2-digit", second: "2-digit"}).replace(/( [0-9]{4}),/, '$1 |')` – Peter Thoeny Jan 14 '23 at 02:15

1 Answers1

1
const date = new Date();
const dateString = date.toLocaleString('en-CA', {
    timeZone: "America/Edmonton", year: "numeric", month: "short",
    weekday: "long", day: "numeric"
});

const timeString = date.toLocaleString('en-CA', {
    hour: "numeric", minute: "2-digit", second: "2-digit"
});

const timeNow = `${dateString} | ${timeString}`

It is still possible some systems may present a different format, in which case you will need to manually create the format as described in: https://stackoverflow.com/a/14638191/5798435

EDD
  • 2,070
  • 1
  • 10
  • 23