Sarotobi
Sarotobi

Reputation: 831

Moment.js how to display the correct date passed from the time to date today

I am new with JavaScript programming and starting to use available libraries I want to display minutes, hours, days, week, months, or year passed since a blog post has been posted.

My date format is below which is stored on a obj.create_at.

2018-09-12 13:12:19

And I am using the moment method below.

moment(obj.create_at, "YYYY-MM-DD HH:mm:ss").fromNow()

But my output is below, which it's not including the whole date.

5 hours ago

Are there any parameters or method that i can use to achieve the correct date/time passed that I should include? Any suggestion would be great!

Upvotes: 0

Views: 681

Answers (3)

Jannomeister
Jannomeister

Reputation: 629

You can use concatenation to achieve that goal. Here's an example to get the minutes, hours, days, weeks, months, and years passed. Hope it helps you mate.

let createdAt = '2018-09-12 13:12:19';

let data = moment(createdAt, "YYYY-MM-DD HH:mm:ss");

let mins = moment().diff(data, 'minutes');
let hours = moment().diff(data, 'days');
let days = moment().diff(data, 'days');
let weeks = moment().diff(data, 'days');
let months = moment().diff(data, 'days');
let years = moment().diff(data, 'years');

console.log("minutes passed: "+mins)
console.log("hours passed: "+hours)
console.log("days passed: "+days)
console.log("weeks passed: "+weeks)
console.log("months passed: "+months)
console.log("years passed: "+years)

Upvotes: 1

Shreesha
Shreesha

Reputation: 71

The API is not meant for your requirement. But still you can tweak it as required by doing string concatenation

Upvotes: 1

etarhan
etarhan

Reputation: 4176

That particular function always will return some type of "blabla time ago" type of format, as stated in their docs: fromNow

Upvotes: 1

Related Questions