Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

moment js extract year from string

Tags:

I'm new to moment.js and I can't really understand the documentation. I'd like to manipulate some dates in string format.

I have my date as string from json feed and looks like:

var year = item.date // it returns a string like "25/04/2012" 

How do I extract the year from it using moment.js ?

like image 675
Mauro74 Avatar asked Oct 04 '12 08:10

Mauro74


People also ask

How do you find the year from a date with a moment?

format('YYYY-MM-DD'); Calling moment() gives us the current date and time, while format() converts it to the specified format. This example formats a date as a four-digit year, followed by a hyphen, followed by a two-digit month, another hyphen, and a two-digit day. );

How do you find the date string from the moment?

js parsing date and time. We can parse a string representation of date and time by passing the date and time format to the moment function. const moment = require('moment'); let day = "03/04/2008"; let parsed = moment(day, "DD/MM/YYYY"); console. log(parsed.

How do you find the month and year in a moment?

var check = moment('date/utc format'); day = check. format('dddd') // => ('Monday' , 'Tuesday' ----) month = check. format('MMMM') // => ('January','February.....) year = check. format('YYYY') // => ('2012','2013' ...)


2 Answers

You can use

moment("25/04/2012","DD/MM/YYYY").format("YYYY") or     moment("25/04/2012","DD/MM/YYYY").year() 

in your example:

moment(item.date,"DD/MM/YYYY").year() 
like image 75
Luca Avatar answered Sep 26 '22 02:09

Luca


Or you can convert the string to date then extract the year:

var date = new Date(dateString); if (!isNaN(date)) {  return d.getFullYear(); } 
like image 40
acabaral Avatar answered Sep 25 '22 02:09

acabaral