skip to Main Content

I have a method which recieves a date as argument in string as following format "20230504". I want to change that date to "2023-05-04".

How can I do this?

4

Answers


  1. I believe your best course of action would be to change the caller method to ensure the data you are receiving is correctly formatted.

    But if that is not possible, you could use something like this

    function format_date(unformatted_date) {
        return unformatted_date.slice(0,4)+'-'+unformatted_date.slice(4,6)+'-'+unformatted_date.slice(6,8);
    }

    I mean, this is not the best way to do it, since you would have to be sure the length and the format is the same every time.

    Anyway, hope it helps

    Login or Signup to reply.
  2. You can try to split the the potential solution into 2 steps:

    1.) Extract the day, month and year, and assign them to different variables. I would suggest using the String.protoype.slice method on the given string for this purpose.

    2.) Concatenate them together and add "-" in between.

    Sample pseudocode:

    given dateStr as input
    
    extract month from dateStr as m
    extract day from dateStr as d
    extract year from dateStr as y
    
    put them together using the format "y-m-d" (yyyy-mm-dd) as formattedStr
    
    return formattedStr as output
    

    Unfortunately this solution will always work if the input is always the same length as your example and that we can assume that the input is always in the format "yyyymmdd".

    Login or Signup to reply.
  3. You could use a regular expression:

    const fixDate = (input) => input.replace(/^(d{4})(d{2})(d{2})$/, '$1-$2-$3')
    
    console.log(fixDate('20230504')) // 2023-05-04
    Login or Signup to reply.
  4. Using slice, map and join

    function hyphenate(str, groups) {
      let temp = 0;
      const segments = groups.map((len) => str.slice(temp, (temp += len)));
      return segments.join("-");
    }
    
    const hyphenateOneLiner = (str, groups, t = 0) =>
      groups.map((len) => str.slice(t, (t += len))).join("-");
    
    const input = "20230504";
    
    const output = hyphenate(input, [4, 2, 2]);
    
    console.log(output);
    
    console.log(hyphenateOneLiner(input, [4, 2, 2]));
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search