-1

i want to change my date format from "20221015T000000Z" to yyyy-mm-dd. i tried looking up solutions but not able to find anything relatable.

  • 4
    What did you try and where are you stuck? – GabeRAMturn Oct 31 '22 at 07:18
  • How is the string `20221015T000000Z` created? Is it returned by any service or do you have control on how it is created? It's not a valid ISO date string. – adiga Oct 31 '22 at 07:20
  • [this](https://stackoverflow.com/questions/23593052/format-javascript-date-as-yyyy-mm-dd) answer can help – mahmoud ettouahri Oct 31 '22 at 07:21
  • @adiga i am getting this from api from rrule value. – priya pathak Oct 31 '22 at 07:22
  • Please add the relevant tag and the code which created this string. There must be a way to generate a valid ISO string from that library. – adiga Oct 31 '22 at 07:25
  • You could match based on the position and get the ISOstring like this: `"20221015T000000Z".replace(/(\d{4})(\d{2})(\d{2}).*/, "$1-$2-$3")`. But, it will be better if the library returns the date in case the string format changes. – adiga Oct 31 '22 at 07:29

1 Answers1

4

The example date string already contains all the information you need in clear text. It's not a standard date string, but assuming the format of the string is always going to be like that, all you have to do is to extract the substrings and stitch them back together using the - separator.

This is exactly what this function does by using String's substr method and Array's join method:

const parseDateString = s => [s.substr(0,4), s.substr(4,2), s.substr(6,2)].join('-');

Usage:

const result = parseDateString('20221015T000000Z');
// do something with result, e.g. console.log(result)
Andrei
  • 1,723
  • 1
  • 16
  • 27