Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
232 views
in Technique[技术] by (71.8m points)

javascript - display day and month, without a year according to locale

Is there any better way for getting only day and month from a date including location appropriate separator?

I have a solution that gets separator first:

 function getDateSep() {
   var temp = moment().format('L');
   var locale = moment().locale;
   var datesep = temp.substring(5, 6);
   return datesep;
}

and then builds the date like this:

var sep = function getDateSep()
var date = date.format('D' + sep + 'M'+ sep)

Is there a solution that builds the whole date dynamically?

The result I want to achieve would be like: 31.01 (dd.mm) 31/01 (dd/mm) 01.31 (mm.dd) 01/31 (mm/dd) etc

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Have you considered using Date#toLocaleDateString instead of monentjs?

It takes a JS Date object and options to output a locale date in the format you specify.

Example:

var date = new Date();
var options = { day: 'numeric', month: 'short' };

console.log(date.toLocaleDateString('en-GB', options));
// outputs: Feb 24

var numeric = { day: 'numeric', month: 'numeric' };

console.log(date.toLocaleDateString('en-GB', numeric));
// outputs: 24/02

As pointed out in the comments, it's worth ensuring that your targeted platforms support the toLocaleDateString approach above with options. For instance, this approach isn't currently supported by Android webview as detailed here for toLocaleDateString's Browser_compatibility


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...