我正在开发一个项目,需要对日期对象进行这种文本响应。
“1天7小时路程”
--- 需要这样 - 而不是“距离 31 小时”或“距离 1 天”
-- 我也在使用 moment js - 因为我正在英语和德语之间进行语言切换 - 所以我已经利用了 moment.js 语言区域设置
moment.locale('de')
我正在使用 moment js - 目前我创建了一个假日期对象
var futureDate = new Date()
futureDate.setDate(futureDate.getDate() + 1)// add a day
futureDate.setHours(7)// add 7 hours
当我尝试渲染时刻 js 时
moment(futureDate).endOf('day').fromNow()
它只是说“一天之内”
如何修改 moment 函数以处理 1 天 7 小时——或者重新调整句子?
--- 代码片段尝试
moment.locale('de') // switch between en and de -- english and german
var futureDate = new Date()
futureDate.setDate(futureDate.getDate() + 1)// add a day
futureDate.setHours(7)// add 4 hours
// Results in hours
console.log(moment(futureDate).endOf('day').fromNow());
<script src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.17.1/moment.min.js"></script>
使用差异进行代码测试2
moment.locale('de') // switch between en and de -- english and german
var a = moment();
var b = moment(a).add(31, 'hours');
// Results in days
console.log(b.diff(a, 'days'));
console.log(b.diff(a, 'days', true));
<script src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.17.1/moment.min.js"></script>
您可以使用relativeTimeThreshold http://momentjs.com/docs/#/customization/relative-time-threshold/ and relativeTime http://momentjs.com/docs/#/customization/relative-time/(键为moment.updateLocale
)自定义时刻如何显示相对时间(例如fromNow()
输出)。
对于您的情况,您可以:
- 调整阈值以获得以秒为单位的差异(请参阅:如何让 moment.js 显示以秒为单位的相对时间? https://stackoverflow.com/q/42216583/4131048).
- 使用创建持续时间对象moment.duration(Number, String) http://momentjs.com/docs/#/durations/creating/.
- Use 时刻-持续时间-格式 http://momentjs.com/docs/#/plugins/duration-format/插件以您喜欢的格式显示持续时间值。
这是一个实时示例:
var momEn = moment().add({d:1, h:7});
var momDe = moment().locale('de').add({d:1, h:7});
console.log(momEn.fromNow()); // in a day
console.log(momDe.fromNow()); // in einem Tag
// Change relativeTimeThreshold
moment.relativeTimeThreshold('s', 60*60*24*30*12);
// Update relative time
moment.updateLocale('en', {
relativeTime : {
s: function (number, withoutSuffix, key, isFuture){
return moment.duration(number, 's').format('d [day] h [hour]');
},
}
});
moment.updateLocale('de', {
relativeTime : {
s: function (number, withoutSuffix, key, isFuture){
return moment.duration(number, 's').format('d [Tag] h [Uhr]');
},
}
});
console.log(momEn.fromNow()); // in 1 day 7 hour
console.log(momDe.fromNow()); // in 1 Tag 7 Uhr
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment-with-locales.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment-duration-format/1.3.0/moment-duration-format.min.js"></script>
不幸的是,您必须手动更新需要支持的每个区域设置。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)