ADV
ADV

Reputation: 189

JS. Get part of date from string

I have this string '2020-10-20' Can i somehow get those numbers separately like this:

const [year, month, day] = '2020-10-20'.match(/\d\d\d\d/ what should i write there?)

Or any better approach exist?

Upvotes: 1

Views: 191

Answers (4)

h-sifat
h-sifat

Reputation: 1595

I'll add a little bit to the above solutions. If you want to get those values as number then use the map method.

const dateString = "2020-10-12";
const [year, month, date] = dateString.split("-").map(Number);
console.log(year, month, date);

Update

By the way, If you want to learn how to do that with regex, then here's how:

const dateString1 = "2020-10-10";
const dateString2 = "2020/10/10";
const dateString3 = "2020_10_10";

const pattern = /(\d{4}).(\d{2}).(\d{2})/;
 /* 
  * \d - matches digits 0 - 9
  * \d{4} - matches any 4 digits. e.g., 1234, 4587 ...
  * \d{2} - matches any 2 digits.
  * . - matches anything except new line ("\n"). For the
  * separator.
  * (anything-here) - anything inside () is called a capture
  * group.
  * and will be available in the result
  * */
 
 /*
  * console.log(pattern.exec(dateString2))
  * returns [ "2020/10/10", "2020", "10", "10" ]
  * now we need to slice the arrary from index 1 to 3
  * and we get [ "2020", "10", "10" ]
  * */
  
function parseDate(dateString) {
  // For invalid dateString we'll throw an error
  if(!pattern.test(dateString))
    throw new Error("Invalid date string");
  return pattern.exec(dateString).slice(1).map(Number);
}
  
console.log(parseDate(dateString1))
console.log(parseDate(dateString2))
console.log(parseDate(dateString3))

  

Upvotes: 1

chrwahl
chrwahl

Reputation: 13070

Or turn the string into a Date object and then return year, month and date.

var date = new Date('2020-10-20');
console.log(date);
console.log(date.getFullYear());
console.log(date.getMonth()+1); // Jaunary = 0
console.log(date.getDate());

Using the date object you also avoid problems with the leading "0" for numbers less than 10.

var date = new Date('2020-02-8'); // notice the "missing" 0 before 8
console.log(date);
console.log(date.getFullYear());
console.log(date.getMonth()+1); // Jaunary = 0
console.log(date.getDate());

Upvotes: 1

Harsh Saini
Harsh Saini

Reputation: 626

Using regex you can do something like this:

console.log('2020-10-20'.match(/\d+/g))

If you want to use Array.prototype.split, you can do something like this

console.log('2020-10-20'.split("-"))

Upvotes: 1

thinkgruen
thinkgruen

Reputation: 1

You can split the string using a delimiter as follows

const [year, month, day] = '2020-10-20'.split("-")

then you would have year=2020 etc.

Upvotes: 2

Related Questions