问题描述
我在我的项目中使用 moment.js 并将日期格式化如下:
i am using moment.js in my project and formatting dates as follows:
var locale = window.navigator.userlanguage || window.navigator.language; moment.locale(locale); somedate.format("l");
效果很好,但有时我需要显示一个没有年份的日期.我不能使用像 somedate.format("mm/dd") 这样的东西,因为在某些语言中它应该是 somedate.format("dd/mm").我需要类似 l,ll,lll 但没有年份的东西.
it works well but sometimes i need show a date without a year. i can't use something like somedate.format("mm/dd") because in some languages it should be somedate.format("dd/mm"). i need something like l,ll,lll but without the year.
我能做什么?
lts : 'h:mm:ss a', lt : 'h:mm a', l : 'mm/dd/yyyy', ll : 'mmmm d, yyyy', lll : 'mmmm d, yyyy lt', llll : 'dddd, mmmm d, yyyy lt'
推荐答案
好的.这有点糟糕,但你知道它会是这样.
okay. this is a little awful, but you knew it was going to be.
首先,您可以访问(例如)'l'的实际格式字符串:
first, you can access the actual format string for (for instance) 'l':
var formatl = moment.localedata().longdateformat('l');
接下来,您可以通过明智的正则表达式替换对其进行一些手术:
next, you can perform some surgery on it with judicious regex replacement:
var formatyearlessl = formatl.replace(/y/g,'').replace(/^w|w$|ww/,'');
(也就是说:删除yyyy,加上删除后留下的孤立分隔符)
(which is to say: remove yyyy, plus the orphaned separator left by its removal)
然后您可以在瞬间格式调用中使用您的新格式字符串:
then you can use your new format string in a moment format call:
somedate.format(formatyearlessl);
这必然做出一些假设:
- 区域设置的月 日数字格式的顺序与该区域设置的年 月 日格式的顺序匹配,但删除了年份.
- 短格式仅在月和日之间使用分隔符(没有前导/尾随分隔符).
- 短数字日期格式的分隔符始终为非字母数字.
- 格式由数字元素和分隔符组成,而不是带有文章的句子格式(请参阅下面 rgpt 关于西班牙语和葡萄牙语的评论,这也适用于其他一些语言的长格式).
快速回顾一下 locale/*.js,这些假设适用于我检查的每个语言环境文件,但可能存在一些违反它们的语言环境.(eta:下面的评论指出德国短日期格式违反了第二个假设)
on a quick review of locale/*.js, these assumptions hold true for every locale file i examined, but there may be some locales that violate them. (eta: a comment below points out that a german short date format violates the second assumption)
另外一个重要的警告是,这很可能是脆弱的.完全有可能moment.js的未来版本会改变当前在longdateformat中的数据位置...
as an additional important caveat, this is likely to be fragile. it is entirely possible that a future version of moment.js will change the location of the data currently in longdateformat...