0

I have a string like this : DD/MM/YYYY and i would like to get the year: YYYY the month: MM and the day: DD.

How can I do this by using javascript or typescript?

I already try to use the javascript function getFullYear() but I can't use this function in the string value. I have to convert the string to date. But I can't find the function.

function converteDate() {
  let date1 = new Date('24/09/2018');
  console.log('Date ---', date1.getFullYear());
}
converteDate();

Thanks for your help.

user107224
  • 205
  • 2
  • 12
Syllaba Abou Ndiaye
  • 213
  • 1
  • 7
  • 21

4 Answers4

2

I'm not sure if this work for your exact needs, but you may try this,

var parts ='24/09/2018'.split('/')
var d = new Date(parts[2], parts[1] - 1, parts[0]);
var n = d.getFullYear();

n holds year.

benjamin c
  • 2,278
  • 15
  • 25
0

If you are sure the input format is always DD/MM/YYYY, you can use this:

// for example: input = '24/09/2018'
var [d, m, y] = input.split('/').map(part => parseInt(part, 10));

console.log(y); // will log an 2018 as a number

This uses a so called destructuring assignment, which requires ES6 support (or TypeScript).

Fabian Lauer
  • 8,891
  • 4
  • 26
  • 35
0
var parts ='24/09/2018'.split('/')
console.log("Parts :" , parts[2]);

Just store parts[2] in any variable.

var year = parts[2]; 
Sachin Shah
  • 4,503
  • 3
  • 23
  • 50
0

Your problem will easily can be solve by using split function in Javascript...split function is used to split the given string into array of strings by separating it into sub strings using a specified separator provided in the argument.After spiting your string, you will have the year in the last index of the returned array.

function convertDate(date){
  let formatted = date.split('/');
  return formatted[formatted.length-1];
}
console.log(convertDate('24/09/2018'));
Aravinda Meewalaarachchi
  • 2,551
  • 1
  • 27
  • 24