1

I have an a date that take from user input in JS(react).

I need to send it in cyymmdd format. how can i convert it ?

like this 01/05/1998 to 980501

EDIT

how can i change it from cyymmdd to dd/mm/yyyy ?

yanir midler
  • 2,153
  • 1
  • 4
  • 16

5 Answers5

1

try this

convertDateFromDDMMYYYYToCYYMMDD('01/05/1998'); //returns desired '980501'

function convertDateFromDDMMYYYYToCYYMMDD(ddmmyyyyDate){
    const testRegex = /^\d{2}\/\d{2}\/\d{4}$/
    if(!testRegex.test(ddmmyyyyDate))
        throw new TypeError('date does not match DDMMYYYY format')
    const dateParts = ddmmyyyyDate.split('/')
    const cyy = Number(dateParts.pop()) - 1900
    if(cyy<0)
        throw new Error('date before year 1900')
    return cyy+dateParts[1]+dateParts[0]
} 
Allure
  • 513
  • 2
  • 12
1

You can use momentjs to do that easy way

moment("11/05/1998").format("YYMMDD");
mouafus
  • 148
  • 7
1

You can join it by splitting the string by / and then reverse the order of the array (of the spitted values) and then join again and cut the first 2 characters:

'01/05/1998'.split('/').reverse().join('').slice(2) // "980501"

Breakdown:

'01/05/1998'
  .split('/') // ["01", "05", "1998"]
  .reverse()  // ["1998", "05", "01"]
  .join('')   // "19980501"
  .slice(2)   //   "980501"
vsync
  • 118,978
  • 58
  • 307
  • 400
0

Assuming that you want to convert it before you save it in your database, I would suggest using RegEx for changing the format.

Look at this thread, It has the answer you are seeking for. Here's a link.

Also, possible duplication.

0

The easiest way is to do with split

const date = "01/05/1998";
const [dd, mm, year] = date.split("/");
const yy = year.match(/\d\d$/)[0];

const result = `${yy}${mm}${dd}`;
console.log(result);
DecPK
  • 24,537
  • 6
  • 26
  • 42