-1

Almost like Node.js - How to format a date string in UTC, as the following is already the format that I want (both of them):

var x = new Date();
console.log(x);
var u = x.toISOString();
console.log(u);

However, the output is in UTC time zone & format (as indicated by the trailing Z), whereas,

I just need it in the local time zone. How to do that?

I've tried .toLocaleDateString(), toLocaleTimeString(), toLocaleFormat("%Y-%m-%d %H:%M:%S"), toString("yyyyMMddHHmmss"), etc, etc, but none is working. pls help. thx.

xpt
  • 20,363
  • 37
  • 127
  • 216

1 Answers1

0

Something like this?

function formatLocal(d) {

  // tzo is minutes, and signed opposite of the
  // usual -06:00 or +03:00 format you're used to
  const tzo = d.getTimezoneOffset()

  // get hours offset
  let tzH = Math.floor(Math.abs(tzo / 60))

  // get minutes offset
  let tzM = tzo % 60

  // pad and negate accordingly
  tzH = (tzH < 10) ? `0${tzH}` : tzH
  tzH = (tzo > 0)  ? `-${tzH}` : tzH
  tzM = (tzM < 10) ? `0${tzM}` : tzM

  // replace Z with timezone offset
  return d.toISOString().replace('Z', `${tzH}:${tzM}`)
}
Ben
  • 571
  • 2
  • 4
  • 15
  • thanks Ben, I don't care about the timezone offset, so the answer from @Bergi's link works for me well. – xpt Jan 23 '18 at 04:39