Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

moment.js reverse .fromNow()

So i'm working with moment.js.

I see you can translate a date into a human-friendly format using moment().fromNow();

Is there a way to do the opposite?

For example, I want to turn this --> "2 weeks ago" into a normal date format or UNIX timestamp.

I sifted through the documentation but couldnt find anything. Any direction would help, thanks.

like image 855
ribsies Avatar asked Oct 24 '25 15:10

ribsies


1 Answers

Depending on how complicated/different the input strings can be, you could do this:

//parse out the number and the duration

var inputString = "2 weeks ago";

var myRegExp = /^(\d+)\s(\w+)\sago$/;

var results = myRegExp.exec(inputString);

var num = results[1];
var duration = results[2];

moment().subtract(duration,num).toString() //or whatever format you prefer

Note this will work for input strings of the format "number duration ago".

Hope that helps!

like image 104
go-oleg Avatar answered Oct 27 '25 04:10

go-oleg



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!