Reputation:
I have a JSON formatted date, say: 2017-08-01T23:28:56.782Z
I've given it fromNow()
to display a relative date a month ago
.
Is there a way to format it to display something like 30d
?
Upvotes: 1
Views: 3998
Reputation: 1226
1 . %d will print no of digits .
2. " " will show Sting Literal . eg : Sec, s , d, y, w .
OUTPUT : 1d , 1w , 1y,
const TIME_ZONE = -1 * new Date().getTimezoneOffset() / 60;
this.getDateFrom("2018-02-22 14:27:56");
getDateFrom(givenDate) {
return moment(givenDate)
.add(TIME_ZONE, "hours")
.fromNow(
updateLocale("en", {
relativeTime: {
future: "in %s",
past: "%s ",
s: "sec",
m: "%d m",
mm: "%d m",
h: "%d h",
hh: "%d h",
d: "%d d",
dd: "%d d",
M: "a mth",
MM: "%d mths",
y: "y",
yy: "%d y"
}
})
);
}
fromNow(true)
: true will trim your format (1 week ago) .
return moment(givenDate)
.add(TIME_ZONE, "hours")
.fromNow(true);
OUTPUT : a day , 1 week , 1 year,
Upvotes: 3
Reputation: 31482
You can use relativeTimeThreshold
to customize thresholds for moment relative time. In your case, you can update the d
property that represents:
least number of days to be considered a month.
If you want to show d
instead of days, you can use customize relativeTime
property with the updateLocale
method.
If you want to remove the suffix (e.g. in / ago) from fromNow
output, you can simply use fromNow(true)
.
Here a working sample:
var m = moment('2017-08-01T23:28:56.782Z');
console.log(m.fromNow());
moment.relativeTimeThreshold('d', 30*12);
moment.updateLocale('en', {
relativeTime : {
dd: "%dd",
}
});
console.log(m.fromNow(true));
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
Upvotes: 4
Reputation: 4214
I think I might be a bit out of date since there are 36 days from your target date.
var a = moment(); // today
var b = moment("2017-08-01T23:28:56.782Z"); // target date
var diffInDays = a.diff(b, 'days') + 'd'; // 36d;
The above code gets your days from the specified target date.
Upvotes: 1