-3

In Javascript, I have a datetime string that looks like:

2021-03-12 19:52:09

How do I convert it so it appears in this format?

03/12 12:34pm PST

Ideally I would like to do so without external libraries.

Evan Hessler
  • 229
  • 2
  • 10
  • If you have a `Date` object, it won't look like that. You have a string. Can you share your code with us? –  Mar 12 '21 at 20:43
  • Work through the top 1 or 2 answers at the duplicates and you'll have learned how to parse the string to a date and how to format it for a particular timezone or location. You should also read the last, which is good general information on parsing timestamps. – RobG Mar 12 '21 at 22:51

1 Answers1

0

You could format it manually like this:

now = Date.now();
pst = new Date(now-(8*60*60*1000)); //-8 hours for pst
pst_str = `${pst.getMonth()}/${pst.getDate()} ${pst.getHours()%12}:${pst.getMinutes()}${pst.getHours()>=12?'pm':'am'} PST`;
jeremy302
  • 658
  • 4
  • 8
  • 1
    This doesn't address parsing the string to a Date, there are much better ways of formatting a Date, e.g. `new Date().toLocaleString('en-US',{month:'2-digit', day:'2-digit', hour:'numeric', minute:'2-digit', timeZone:'America/Los_Angeles', timeZoneName:'short'})` which gives something like "03/12, 2:58 PM PST". – RobG Mar 12 '21 at 22:58