0

I have date data in below format

2020-10-07 05:21:15.

I want to convert it into Wed,7 Oct'20 -05:21pm.

I tried with regex

(new Date(2020-10-07 05:21:15)).toString().replace(/\S+\s(\S+)\s(\d+)\s(\d+)\s.*/,'$1 $2,$3')

But im getting output Oct7,2020,

Can anyone help me out with javascript or regex to format it.

  • `(new Date('2020-10-07 05:21:15')).toString().replace(/\S+\s(\S+)\s(\d+)\s(\d+)\s.*/,'$1 $2,$3')` resolves to `Oct 07,2020` for me – Wex Oct 08 '20 at 20:54
  • use moment js for all your date time needs – ifelse.codes Oct 08 '20 at 20:58
  • You can get something close with this: `new Intl.DateTimeFormat('en-GB', {weekday: 'short', year: '2-digit', month: 'short', day: 'numeric', hour: 'numeric', minute: 'numeric', hour12: true}).format(new Date())` But it's not your precise format. If you need that, then look to building it yourself from the constituent parts. – Scott Sauyet Oct 08 '20 at 21:43
  • Please do not use the built–in parser, particularly for unsupported formats, see [*Why does Date.parse give incorrect results?*](https://stackoverflow.com/questions/2587345/why-does-date-parse-give-incorrect-results). In Safari at least, `new Date('2020-10-07 05:21:15')` produces an invalid date. – RobG Oct 08 '20 at 22:55

1 Answers1

0

Try this

const date = new Date();

// First option

const time = new Intl.DateTimeFormat('en', { hour: '2-digit', minute: '2-digit', }).format(date);
const dayWord = new Intl.DateTimeFormat('en', { weekday: 'short' }).format(date);
const dayNumber = new Intl.DateTimeFormat('en', { day: 'numeric' }).format(date);
const month = new Intl.DateTimeFormat('en', { month: 'short' }).format(date);
const year = new Intl.DateTimeFormat('en', { year: '2-digit' }).format(date);
console.log(`${dayWord},${dayNumber} ${month}'${year} -${time}`);

// Second option with format to parts method

const formatter = new Intl.DateTimeFormat('en', {
  year: '2-digit',
  day: 'numeric',
  month: 'short',
  weekday: 'short',
  hour: '2-digit', 
  minute: '2-digit'
}).formatToParts(date);

var customDateString = `${formatter[0].value},${formatter[4].value} ${formatter[2].value}'${formatter[6].value} -${formatter[8].value}:${formatter[10].value}${formatter[12].value.toLowerCase()}`;

console.log(customDateString);
svyat1s
  • 868
  • 9
  • 12
  • 21
  • How can i get Time along with this ? like Wed,7 Oct'20 - 05:21pm. time in am and pm format @svyatis.Iviv – raj rajaji Oct 08 '20 at 21:04
  • 2
    You could shorten that and make it hugely more efficient using a single instance of *Intl.DateTimeFormat* and the [*formatToParts* method](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/formatToParts) to get the parts. – RobG Oct 08 '20 at 22:57
  • @rajrajaji I've updated answer with time – svyat1s Oct 09 '20 at 06:25
  • also updated with format to parts method option as @RobG mentioned – svyat1s Oct 09 '20 at 06:57