Convert date from yyyyymmdd to dd/mm/yyyy

Asked

Viewed 79 times

0

I have a string with the following value: 20191219 this is a date in the format month and day, I wanted to know how to transform it to the format day/month/year, using the value I mentioned, would 19/12/2019.

Searching the internet I saw that has Date.parse(), but it would only work if this string was broken with spaces, / or -

I thought of using substring to capture the positions, taking the year, month and day, and with that assemble in the format I want, however, I imagine that there should be an easier way to do this.

2 answers

2


If the date is always in format YYYYMMDD, you can use a regular expression to do the match of each individual part of the date.

Something like that:

function parseDate(dateString) {
  const [, year, month, day] = dateString.match(/(\d{4})(\d{2})(\d{2})/)
  
  return `${day}/${month}/${year}`;
}

console.log(parseDate('20191219'));

Basically, we create the following regular expression:

/(\d{4})(\d{2})(\d{2})/

It has three groups:

  • The first of them, which corresponds to the year, formed by 4 digits - captured by \d{4}, which means 4 digits;
  • The second group, which corresponds to the month, formed by 2 digits - captured by \d{2};
  • And the last of them, corresponding to the day, formed by 2 digits - also captured by \d{2}.

Then we use the method match. To learn more about him, read the documentation of String.prototype.match.

  • Ball show, thank you very much, knew that would have a more effective way, with this I can even do the reverse way to save a new date in the bank

1

Guy got around this problem in my system in a simpler way

I have an input:

<input type="text" class="form-control input-default" placeholder="Data final de pagamento" name="data_vencimento" required="required"  maxlength="10" onkeypress="mascaraData(this)">

In the database I declared a varchar of 10 and input put a maxlength="10"

Ai fez uma mascaraData(this) em javascript

<script type="text/javascript">
    function mascaraData(data){ 
        if(data.value.length == 2)
            data.value = data.value + '/'; 
        if(data.value.length == 5)
            data.value = data.value + '/';
    }
</script>

Every time the person type he will high increment the bars and will limit to 10 digits and in the database as it will be varchar, he will save the date in Brazilian format.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.