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 ?
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 ?
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]
}
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"
'01/05/1998'
.split('/') // ["01", "05", "1998"]
.reverse() // ["1998", "05", "01"]
.join('') // "19980501"
.slice(2) // "980501"
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.
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);