12 hour time conversion

JavaScript (ES6), 69 bytes

d=>new Date(d).toLocaleString(0,{hour:n='numeric',minute:n,hour12:1})

f=
d=>new Date(d).toLocaleString(0,{hour:n='numeric',minute:n,hour12:1})
console.log(
  f('Fri Jun 30 2017 21:14:20 GMT-0700 (PDT)'),
  f('Fri Jun 30 2017 00:10:23 GMT-0700 (PDT)'),
  f('Fri Jun 30 2017 12:10:23 GMT-0700 (PDT)'),
  f('Sat Jun 31 2018 8:06:20 GMT-0700 (PDT)'),
  f('Fri Jul 01 2017 01:14:20 GMT-0700 (PDT)'),
  f('Sat Apr 10 2020 09:06:20 GMT-0700 (PDT)'),
)


JavaScript (ES6), 58 55 bytes

Assumes you are in the United States.

d=>new Date(d).toLocaleTimeString().replace(/:.. /,' ')

f=
d=>new Date(d).toLocaleTimeString().replace(/:.. /,' ')
console.log(
  f('Fri Jun 30 2017 21:14:20 GMT-0700 (PDT)'),
  f('Fri Jun 30 2017 00:10:23 GMT-0700 (PDT)'),
  f('Fri Jun 30 2017 12:10:23 GMT-0700 (PDT)'),
  f('Sat Jun 31 2018 8:06:20 GMT-0700 (PDT)'),
  f('Fri Jul 01 2017 01:14:20 GMT-0700 (PDT)'),
  f('Sat Apr 10 2020 09:06:20 GMT-0700 (PDT)')
)


JavaScript (ES6), 81 78 bytes

Answer before outputting a leading 0 in single-digit hours was made optional and test cases without leading 0s were added.

d=>([m,s]=d.slice(16).split`:`,`0${m%12||12}:${s} ${m<12?'A':'P'}M`.slice(-8))

f=
d=>([m,s]=d.slice(16).split`:`,`0${m%12||12}:${s} ${m<12?'A':'P'}M`.slice(-8))
console.log(
  f('Fri Jun 30 2017 21:14:20 GMT-0700 (PDT)'),
  f('Sat Jun 31 2018 08:06:20 GMT-0700 (PDT)'),
  f('Fri Jul 01 2017 01:14:20 GMT-0700 (PDT)'),
  f('Sat Apr 10 2020 09:06:20 GMT-0700 (PDT)')
)


Python 2, 66 bytes

lambda s:`int(s[15:18])%12`+s[18:21]+'  APMM'[int(s[15:18])>11::2]

Try it online!


sh + coreutils, 22 bytes

date +%I:%M\ %p -d"$1"

(If seconds are allowed, then date +%r -d"$1" suffices.)

Tags:

Code Golf