Avanae
Avanae

Reputation: 21

.JS change date YYYY/MM/DD to DD/MM/YYYY

I'm creating a passport script that notes a user's first, last name, date of birth and height. However I cannot get it to work other than using YYYY/MM/DD. js not is my strong suit and it's been breaking my head for the last couple of hours.

The original code relating to everything focussed on the Date of Birth is:

'use strict'
const DATE_FORMAT = '****/**/**'
const DATE_PLACEHOLDER = 'YYYY/MM/DD'

const birthdate = document.querySelector('#birthdate')
function DoFormat(x, pattern, mask) {
  var strippedValue = x.replace(/[^0-9]/g, '')
  var chars = strippedValue.split('')
  var count = 0

  var formatted = ''
  for (let i = 0; i < pattern.length; i++) {
    const c = pattern[i]
    if (chars[count]) {
      if (/\*/.test(c)) {
        formatted += chars[count]
        count++
      } else {
        formatted += c
      }
    } else if (mask) {
      if (mask.split('')[i])
        formatted += mask.split('')[i]
    }
  }
  return formatted;
}

function Format() {
  const val = DoFormat(birthdate.value, DATE_FORMAT)
  birthdate.value = DoFormat(birthdate.value, DATE_FORMAT, DATE_PLACEHOLDER)

  if (birthdate.createTextRange) {
    var range = birthdate.createTextRange()
    range.move('character', val.length)
    range.select()
  } else if (birthdate.selectionStart) {
    birthdate.focus()
    birthdate.setSelectionRange(val.length, val.length)
  }
}

Format()

birthdate.addEventListener('input', Format)
   if (field.id === 'birthdate') {
      if (/^\d\d\d\d\/\d\d\/\d\d$/.test(field.value)) {
        let [yyyy, mm, dd] = field.value.split('/').map(p => parseInt(p, 10))
        mm -= 1
        const date = new Date(yyyy, mm, dd)
        if (date.getMonth() === mm && date.getDate() === dd && date.getFullYear() === yyyy) {
          if (date.getFullYear() >= LOWEST_YEAR && date.getFullYear() <= HIGHEST_YEAR) {
            return true
          }
        }
      }

      this.Error(field)
      return false
    }

changing the DATE_FORMAT or the expression does not yield any results. Anyone have a clue? I also would love to use DD-MM-YYYY rather than DD/MM/YYYY but DD/MM/YYYY is better than nothing.

Upvotes: 0

Views: 405

Answers (1)

Spectric
Spectric

Reputation: 32002

An easier way would just be to split the string by / and reverse the resulting array, then join back together by /:

function reformat(str){
  return str.split('/').reverse().join('/');
}

console.log(reformat("10/11/1213"))

Upvotes: 4

Related Questions